bit fileds or bit manuplation

S

surendra

hi,
i have to maintain a no of 1 bit flags.So i have two approaches
1) using bit fileds:
typedef struct flags_{
unsigned int f_1: 1;
unsigned int f_2: 2;
.
.
.
} flags;
and then i can simply set or reset these flags by
flags myflags;
myflags.f_1 = 1;
myflag.f_2 = 0 ; and so on ..

2) the other approach is to take a simple variable and write some
macros to manuplate bits in it.
unsigned int flags;
#define SET(flags, i ) (flags | (0x01 <<i))
#define RESET(flags,i) (flags &~(0x01<<i))


so the question is which way i should go ? Is there any portability
issue with bit fields.
 
I

Ian Collins

surendra said:
hi,
i have to maintain a no of 1 bit flags.So i have two approaches
1) using bit fileds:
typedef struct flags_{
unsigned int f_1: 1;
unsigned int f_2: 2;
.
.
.
} flags;
and then i can simply set or reset these flags by
flags myflags;
myflags.f_1 = 1;
myflag.f_2 = 0 ; and so on ..

2) the other approach is to take a simple variable and write some
macros to manuplate bits in it.
unsigned int flags;
#define SET(flags, i ) (flags | (0x01 <<i))
#define RESET(flags,i) (flags &~(0x01<<i))


so the question is which way i should go ?

Which ever you prefer, assuming the flags are just flags and don't map
to some external structure.
Is there any portability issue with bit fields.
Again, not unless the flags map to some external structure.
 
P

pete

surendra said:
hi,
i have to maintain a no of 1 bit flags.So i have two approaches
1) using bit fileds:
typedef struct flags_{
unsigned int f_1: 1;
unsigned int f_2: 2;
.
.
.
} flags;
and then i can simply set or reset these flags by
flags myflags;
myflags.f_1 = 1;
myflag.f_2 = 0 ; and so on ..

2) the other approach is to take a simple variable and write some
macros to manuplate bits in it.
unsigned int flags;
#define SET(flags, i ) (flags | (0x01 <<i))
#define RESET(flags,i) (flags &~(0x01<<i))

so the question is which way i should go ?

I prefer the second.
Is there any portability issue with bit fields.

This is what K&R2 section 6.9 Bit-fields, says about masking:
"... these idioms are readily mastered ..."

This is what K&R2 section 6.9 Bit-fields says about bit-fields:
"Almost everything about fields is implementation-dependent"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top