-
struct - bit fields
Hi All..
I have a question regarding the use of bit fields in C. If one declares a struct as bit-field, how do you set all the bits, w/o having to set each one individually.
For example, below is my struct:
struct bitwise_byte {
unsigned b0: 1;
unsigned b1: 1;
unsigned b2: 1;
unsigned b3: 1;
unsigned b4: 1;
unsigned b5: 1;
unsigned b6: 1;
unsigned b7: 1;
} byte;
A short char is of length 8-bits(byte). I want to assign it to this bitfield, so I can access each bit individually. However, I can't do it like this:
short char ch;
byte = ch; //this is INVALID
I want to break a byte up into 8-bits, so I can monitor/control each bit. I figure, bitfields would be how to do.
Anyone, have any suggestions or solutions?
Thanks.
~jc
-
You could use a union
Code:
#include <stdio.h>
union both {
struct {
unsigned b0: 1;
unsigned b1: 1;
unsigned b2: 1;
unsigned b3: 1;
unsigned b4: 1;
unsigned b5: 1;
unsigned b6: 1;
unsigned b7: 1;
} bits;
unsigned char byte;
};
int main ( ) {
union both var;
var.byte = 0xAA;
if ( var.bits.b0 ) {
printf("Yes\n");
} else {
printf("No\n");
}
return 0;
}
> I want to break a byte up into 8-bits, so I can monitor/control each bit. I figure, bitfields would be how to do
Bear in mind that b0 might correspond to 0x80 on one machine, and 0x01 on another machine. The order of bit fields is implementation specific.
-
Or you could do mapping. A structure is nothing but a piece of memory. Define a pointer to a block of the same size give this block a value. Then map the structure onto the block and assign it to the variable of that structure type. Hmm, hope this is understandable English. :-)
Anyway, here's an example which shows what I mean:
Code:
#include <stdio.h>
typedef struct
{
unsigned b1:1;
unsigned b2:1;
unsigned b3:1;
unsigned b4:1;
unsigned b5:1;
unsigned b6:1;
unsigned b7:1;
unsigned b8:1;
} byte_s;
int main()
{
byte_s bfbyte;
unsigned char *ucbyte;
*ucbyte = 0x00;
bfbyte = *((byte_s *) (ucbyte));
printf ("%d %d %d %d : %d %d %d %d \n",
bfbyte.b1, bfbyte.b2, bfbyte.b3, bfbyte.b4,
bfbyte.b5, bfbyte.b6, bfbyte.b7, bfbyte.b8);
*ucbyte = 0xFF;
bfbyte = *((byte_s *) (ucbyte));
printf ("%d %d %d %d : %d %d %d %d \n",
bfbyte.b1, bfbyte.b2, bfbyte.b3, bfbyte.b4,
bfbyte.b5, bfbyte.b6, bfbyte.b7, bfbyte.b8);
return 0;
}
-
Or you could memset it.
Quzah.
-
If you were using C++ classes you could alter its = operation to accept a char. I know this is a C forum, just my 2 cents.