Click to See Complete Forum and Search --> : using C++ i want to change or view or whatever individual bits in a byte. ?possible?


siqe
11-15-2000, 02:01 PM
what if i want to use memory conservatively and hold 8 true/false values in a byte. how can i look at them induvidualy.

i could treat it as an integer and convert it and just hold an array of 1 and 0.

but i was wondering if there is a built in such and such that does this a little easier and a little faster.

anybody know?

kmj
11-15-2000, 02:21 PM
You can do this with bitmasks. For example:
Then just do a bitwise AND against your variable
edit: changed erroneous "bitmaps" to "bitmasks"


#define BIT0 0x01 //(all bits except 1st are 0)
#define BIT1 0x02 //(all bits except 2nd are 0)
#define BIT2 0x04 //(all bits except 3rd)
#define BIT3 0x08 //(4th)
#define BIT4 0x10 //(5th)
#define BIT5 0x20 //(6th)
#define BIT6 0x40 //(7th)
#define BIT7 0x80 //(8th)

typedef usigned car BYTE;

BYTE byteVar = 0;
....
if (byteVar & BIT4) {
printf("Bit 4 is true");
}
else {
printf("bit 4 is false");
}


You can also do the same thing with bitwise shifts.


#define BIT0 0
#define BIT1 1
#define BIT2 2
#define BIT3 3
#define BIT4 4
#define BIT5 5
#define BIT6 6
#define BIT7 7


if (byteVar & (1 << BIT4)) {
printf(" bit 4 is set");
}
else {
printf(" bit 4 is cleared");
}


Either way...
(someone let me know if I messed this up...)




[This message has been edited by kmj (edited 15 November 2000).]

kmj
11-15-2000, 03:41 PM
Oh yeah...

to set a bit, bitwise OR the (|) with the appropriate bitmask,
byteVAR = byteVAR | BIT4;

to clear it, flip the bits in the mask and AND (&) it:
byteVAR = byteVAR & NOTBIT4;

where NOTBIT4 is the XOR of bit 4 (11110111); I think you can get the XOR using ^, but I haven't actually done that myself.

LloydM
11-16-2000, 04:09 AM
Like kmj said, use bitmap operators:
>> Right shift
<< Left shift
& And
| Or
^ Xor
~ Negation (Not)


[code]
unsigned char x;

/* setting bit 5 */
x = x | (1 << 5-1);
or
x |= (1 << 5-1);
or
x = x & 0x10;

/* clearing bit 5 */
x = x & ~(1 << 5-1);

etc,...
[code]

Just be careful but signs when doing right shift. Usually you want an unsigned quantity. If you have a good book on C, look at bit-shift operators and unsigned types.