View Single Post
  #2   Spotlight this post!  
Unread 08-01-2004, 09:52
seanwitte seanwitte is offline
Registered User
None #0116
Team Role: Engineer
 
Join Date: Nov 2002
Location: Herndon, VA
Posts: 378
seanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant futureseanwitte has a brilliant future
Send a message via AIM to seanwitte
Re: Extracting Individual bits in C

You could round out the set by providing macros to set a bit value and clear a bit value. This would be useful if you have a byte with individual flag bits. var is a value and bit is the bit position you're working with. Bit 0 is the least significant bit (on the far right-hand side).

Code:
//get a bit from a variable
#define GETBIT(var, bit)	(((var) >> (bit)) & 1)

//set a bit to 1
#define SETBIT(var, bit)	var |= (1 << (bit))

//set a bit to 0
#define CLRBIT(var, bit)	var &= (~(1 << (bit)))
<edit>
Dave had a good point, added parens around arguments. Left the parens out of SETBIT and CLRBIT since var needs to be a left hand argument. Will leave the conversion to functions to you all, but logic is the same.

We have a union to match the PBASIC BYTE variable type that is bit-addressable. Its not portable but works with the PIC controllers. You can pull out the 8-bit value using the byte field or get a single bit using b0 - b7. Makes a handy way to track a set of flags.

Code:
//byte, addressable bits
//size: 8 bits (1 byte)
//range: 0 to 255
typedef union {
    struct {
        unsigned b0:1;
        unsigned b1:1;
        unsigned b2:1;
        unsigned b3:1;
        unsigned b4:1;
        unsigned b5:1;
        unsigned b6:1;
        unsigned b7:1;
    };
    uchar byte;
} byte;
</edit>

Last edited by seanwitte : 08-01-2004 at 11:33.