// BIT STUFFING in C and C++ // Something that I should have mentioned on Tuesday #include struct sexpression { unsigned int type: 3; // range is 0 to 7 unsigned int inuse: 1; // only used during garbage collection int value: 28; // range will only be +/- 134,000,000. }; // the size of an sexpression object is only 4 bytes, whcih is // nice and efficient on today's computers, but those 32 bits // are divided up 3:1:28 amongst three components. All the packing // and unpacking is done automatically for you, so you don't // have to bother with all the fiddly shifting and bitwise anding. void main() { printf("size = %d bytes\n", sizeof(sexpression)); sexpression s; s.type = 5; s.value = 123456; printf("%d %d %d (5, ?, 123456)\n", s.type, s.inuse, s.value); s.value = 2000000000; printf("%d %d %d (5, ?, 2000000000)\n", s.type, s.inuse, s.value); s.type = 11; s.value = -5; printf("%d %d %d (11, ?, -5)\n", s.type, s.inuse, s.value); s.type = 3; s.inuse = 1; printf("%d %d %d (3, 1, -5)\n", s.type, s.inuse, s.value); s.inuse = 0; printf("%d %d %d (3, 0, -5)\n", s.type, s.inuse, s.value); } /* this is the output produced size = 4 bytes 5 0 123456 (5, ?, 123456) 5 0 120951808 (5, ?, 2000000000) 3 0 -5 (11, ?, -5) 3 1 -5 (3, 1, -5) 3 0 -5 (3, 0, -5) */