Help with finding bit states?

Status
Not open for further replies.

Justin

Posts: 914   +0
Ok, I'm learning C++ (teaching myself). I understand code, I know HTML very well and other things, however most of what I knew was higher then C++, so I never learned how to translate that. I eventually plan to move on to Assembler, but I'd rather get c++ down first. My problem is this.

How do I determine the state of the bits from a hex offset? For instance, if I have 0x1ff, or 0x1fe, or 0xfff, how do I determine what the bits are at that moment?

Thanks a lot!
 
So you want to check individual bits in a number or individual bits in a bit array?

For checking bits, you use the bitwise AND (&).

If you want to chek for the first bit (LSB), you & the number with 0x1 (0000 0001 binary).
If the result is zero (false), the bit was not set.

if(chicken & 0x2) { // If bit 2 is set, do something

For the second bit, you & the number with 0x2 (0000 0010 binary) .
For the third bit, use constant 0x4 (0000 0100 binary).

If you want to set bits, use the bitwise OR (|).

Set first bit in varaible 'chicken':
chicken |= 0x1;

For clearing bits, AND with inversed constants.

Clear bit #4 in 'chicken':
chicken &= 0xF7; // 1111 0111 binary

If you want to flip a bit, use XOR (^).
Flip bit 2 in 'chicken':
chicken ^= 0x2;

Some compilers also support some less standard ways of accessing individual bits
(Borland for example), that are somewhat simpler to use.

If you hava a huge array of bits, and want to find the value of nth bit in that array:

- Divide the bit offset by 8 , you'll get a byte offset to the previous byte.
- Read the next byte.
- Use the remainder from the division in a 'switch' to get access to individual bits.


Of course, you could serach the net and find heaps of libraries containing functions
to do bit manipulations and save yourself the trouble.
 
Status
Not open for further replies.
Back