/* Illustrates the concept of 'union' in C (also supported in C++). The same 32 bit can be accessed as a 32-bit integer or 4 bytes or 32 bits. Compilation: % gcc -ansi bitbyte.c -o executablefilename */ #include typedef struct { unsigned b3: 8, b2: 8, b1: 8, b0 : 8; } word_bytes; typedef struct { unsigned b31: 1, b30: 1, b29: 1, b28: 1, b27: 1, b26: 1, b25: 1, b24: 1, b23: 1, b22: 1, b21: 1, b20: 1, b19: 1, b18: 1, b17: 1, b16: 1, b15: 1, b14: 1, b13: 1, b12: 1, b11: 1, b10: 1, b9 : 1, b8 : 1, b7 : 1, b6 : 1, b5 : 1, b4 : 1, b3 : 1, b2 : 1, b1 : 1, b0 : 1; } word_bits; typedef union { int i; word_bytes byte; word_bits bit; } word; /* word is the type name for this union definition */ main() { word w = {0}; /* all 32 bits are initialized to zeroes */ void bit_print(int); w.bit.b8 = 1; /* assign 1 to 8th bit */ w.byte.b0 = 'B'; /* assign 'B' to 0th byte */ printf("w.i = %d\n", w.i); bit_print(w.i); } void bit_print(int v) /* print the integer parameter value in binary format */ { int intsize = 32, i, mask = 1 << (intsize - 1); /* mask = 100 ... 0 */ for(i = 1; i <= intsize; ++i) { putchar(((v & mask) == 0) ? '0' : '1'); v <<= 1; /* left shift v by one position; vacant bit is filled with 0 */ if ((i % 8) == 0) putchar(' '); } putchar('\n'); } /* Output ====== w.i = 322 00000000 00000000 00000001 01000010 */