: How can I access to each bit in an integer type or byte? For example, suppose that we want to set the 2nd bit of a byte to 1 and first bit to zero. How can I do so? Thanks
:
The quickest way is to use the logical AND, OR, XOR. OR is then used as an addition, AND as a subtraction, and XOR as a switch. Each bit is represented by its decimal code:
Bit Code
1 $01 // Hexidecimal numbers
2 $02
3 $04
4 $08
5 $10
6 $20
7 $40
8 $80
To access a single bit use the AND:
i := $55 and $01; // i contains least significant bit
To set a specific bit use the OR:
i := i or $02; // i second least significant bit is set
Switching a bit:
i := i xor $01; // the least significant bit either cleared if set
// or set if it was cleared
To subtract a bit, use AND with the complement bit mask. The complement bit mask is all bits set, except the ones you want to clear.
i := i and ($FF-$08); // removes the 4th bit