Bit Fields

Wm E Davidsen Jr davidsen at crdos1.crd.ge.COM
Thu Nov 16 01:46:05 AEST 1989


In article <20690 at mimsy.umd.edu>, chris at 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 at 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



More information about the Comp.lang.c mailing list