View Single Post
  #4   Spotlight this post!  
Unread 08-01-2004, 12:46
Noah's Avatar
Noah Noah is offline
Code Monkey
#0861 (The Gondobots)
Team Role: Programmer
 
Join Date: Apr 2002
Location: Venice, California
Posts: 139
Noah has a spectacular aura aboutNoah has a spectacular aura about
Send a message via AIM to Noah
Re: Extracting Individual bits in C

Quote:
Originally Posted by seanwitte
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)))
I think that you've got a slight problem here: I suspect that the expression where (bit) is needs to be replaced with (bit - 1)

Example: Try to access the 3rd bit of 20. 20 = 00010100
00010100 >> 3 == 00000010, but
00010100 >> 2 == 00000101, yielding the correct digit in the correct place.
However, without the ternary operation here, you are likely to return a number of non-binary answers: as you just saw, running GETBIT (20, 3) would yield 2 as you have it written, or five after the (bit-1) correction.

One other correction: The comments you used are C++ style, and not valid in C. watch out!

I believe that corrected macos follow:
Code:
/* get a bit from a variable*/
#define GETBIT(var, bit)	(( var & (1 << (bit-1) ) ) ? 1 : 0 )

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

/* set a bit to 0 */
#define CLRBIT(var, bit)	(var &= (~(1 << (bit-1))))
__________________
"It's broken? NOOAAHH!!! This is your doing, isn't it!"

"We can fix it in the software!"
"It's a BROKEN GEAR!"