Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!mailrus!uwm.edu!uakari.primate.wisc.edu!aplcen!uunet!crdgw1!crdos1!davidsen From: davidsen@crdos1.crd.ge.COM (Wm E Davidsen Jr) Newsgroups: comp.lang.c Subject: Re: Bit Fields Message-ID: <1621@crdos1.crd.ge.COM> Date: 15 Nov 89 14:46:05 GMT References: <89111105491001@masnet.uucp> <20690@mimsy.umd.edu> Reply-To: davidsen@crdos1.UUCP (bill davidsen) Organization: GE Corp R&D Center Lines: 57 In article <20690@mimsy.umd.edu>, chris@mimsy.umd.edu (Chris Torek) writes: [ A lot of useful code to break up arbitrary data into bits ] I usually compromise and just force the store by bytes, LSB first. The technique is virtually the same, except that for portability I assume that the byte size is 8 (can't be smaller, and makes the access easier). Then: typedef char bitz[sizeof unsigned long]; bsave(val, dest) register unsigned long val; bitz dest; { register int n = 0; while (n < sizeof(unsigned long)) { dest[n++] = val & 0xff; val >>= 8; } } /* set a bit */ void setbit(val, dest, bitnum) unsigned val, bitnum; bitz dest; { register int offset = val >> 3, shift = val & 7; register int temp = dest[offset]; temp = (temp & ~(1 << shift) | ((val & 1) << shift); dest[offset] = temp; } /* get a bit, 0 or 1 */ int getbit(dest, nitnum) bitz dest; unsigned bitnum; { return (dest[val >> 3] & (1 << (val & 7))) != 0; } Now this method will make testing or setting the bits considerable slower, but save some space for the storage of the data. Hopefully this information complements the original posting to provide a starting point for doing bit manipulation. Warning!!! I typed this in rather than pull it from a working program. It is modulo any typos. -- bill davidsen (davidsen@crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen) "The world is filled with fools. They blindly follow their so-called 'reason' in the face of the church and common sense. Any fool can see that the world is flat!" - anon