I have a bit field struct as below
but there are only 26 bit fields and it is a size of 32 bits, I am wondering will there be any problem?
Is there a faster way of assigning values to the bit fields? other than channels.bB1 = 1 and so on and so forth?
If you are just assigning one bit field to another, it should work fine. It doesn't matter if there is padding in the structure. Now if you flat write it to a file, take it over to some other system, and flat read it back in, you might not get what you wrote out, but other than that you should be fine.
hmm. This will be passed as a byte stream and on the other side, read the byte stream as the same as above
Originally Posted by quzah
Then things could get a little sticky, unless you are careful about endian issues.
if its big endian, how do i go about assigning values to it?
just like this?
if i want to pass this struct as a byte stream, do I do this
Not sure about the padding of 6 bits to fulfill the 32 bit size. =(
> if its big endian, how do i go about assigning values to it?
> just like this?
> channels.bB1 = 1
Yes, and that has nothing to do with what endian the machine is, or how the compiler decided to pack the bits.
> if i want to pass this struct as a byte stream, do I do this
Not if you want the code to be portable.
To be portable, you have to unpack the bit field structure one member at a time, and repack in a known format.
So something like
unsigned long sendthis = 0;
sendthis = channels.bB1 | ( channels.bB2 << 1 )
and so on.
Bit fields are pretty much a legacy relic from the past. It sounds good, but almost everything about how they are stored is implementation specific. Which means they're all but useless if you intend to use them to communicate data with something outside the program.
Their real utility stems from the days when C was first invented, and say 64KB of memory was considered a luxury. Packing data into as few bits as possible was a good thing.
I think you would be better off with just having an unsigned long, and a few macros like
Which might actually be a bit simpler than having 20+ separate names for things.
#define SETBIT(var,pos) var |= (1ul << pos )
#define CLRBIT(var,pos) var &= (~(1ul<<pos))
#define GETBIT(var,pos) ( var >> pos ) & 1