We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
Hi, sorry i know, this question is an evergreen. I have 320 bitfield variables, which i want to access as single Bit's on one hand, and as a field of 40 byte via RS-232 on the other hand. Yes i know this could be very critical, because every compiler could handle this on his own way. But portability is not so important for me, just want to see my little toy working :-) My hope is that someone can show me a code-example, how to declare, define and operate this. I worked with my textbook, but i'am no native english speaker, so i maybee missunderstood the point. Oh i tried so hard on this special topic, please help. Best regards
union BAG_O_BITS { struct { unsigned bit_000:1; unsigned bit_001:1; /* 316 more ... */ unsigned bit_318:1; unsigned bit_319:1; } bits; unsigned char bytes[40]; } bob; void foo(void) { extern tx(unsigned char *p, unsigned char n); bob.bits.bit_000 = 1; bob.bits.bit_325 = 0; tx(bob.bytes, sizeof bob.bytes); }
s/325/319/
Dear Dan, thank you very much for your help, this works perfect. :-) I'am very happy!
what is :s/325/319/?
i guess replace 325 by 319? Is this a kind of HTML?
Best regards
Hi, One additional question: How can i avoid something like
printf("%u",bob.bits.bit_000); printf("%u",bob.bits.bit_001); printf("%u",bob.bits.bit_002); printf("%u",bob.bits.bit_318); printf("%u",bob.bits.bit_319);
can i have access to the single bits in a loop by something like:
union BAG_O_BITS { struct { unsigned char:1; } bit_x[320]; unsigned char bytes[40]; unsigned int word32[10]; } bob;
for(i=0;i<319;i++) printf("%u ",bob.bit_x[i]);
? I got no error-message but the responce on Hyperterminal was 66556 66556 66556 66556.... :-( where's the mistake?
"what is :s/325/319/?
i guess replace 325 by 319? Is this a kind of HTML?"
's' is the substitute command for editors like ed, sed, and their kind. You'll often run across sed being used in makefiles and build systems.
"How can i avoid something like ...
can i have access to the single bits in a loop ..."
The bits can be accessed from the byte array, so assuming the bitfields are allocated from MSBit to LSBit:
#include <stdio.h> union BAG_O_BITS { struct { unsigned bit_000:1; unsigned bit_001:1; /* 316 more ... */ unsigned bit_318:1; unsigned bit_319:1; } bits; unsigned char bytes[40]; } bob; void foo(void) { unsigned char i, byte, mask; for (i = 0; i != sizeof bob.bytes; i++) { byte = bob.bytes[i]; mask = 0x80; do { printf("%c ", (byte & mask) ? '1' : '0'); } while ((mask >>= 1) != 0); } }
Thanks, but is my first solution for accessing these bitfield in a loop absolutly wrong? :-)
"but is my first solution for accessing these bitfield in a loop absolutly wrong?"
The one with the following as part of the union?
struct { unsigned char:1; } bit_x[320];
Then, yes. An array of 1-bit structs is not "packed".