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
: 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: [code] Bit Code 1 $01 // Hexidecimal numbers 2 $02 3 $04 4 $08 5 $10 6 $20 7 $40 8 $80 [/code] To access a single bit use the AND: [code] i := $55 and $01; // i contains least significant bit [/code] To set a specific bit use the OR: [code] i := i or $02; // i second least significant bit is set [/code] Switching a bit: [code] i := i xor $01; // the least significant bit either cleared if set // or set if it was cleared [/code] 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. [code] i := i and ($FF-$08); // removes the 4th bit [/code]
Comments
:
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:
[code]
Bit Code
1 $01 // Hexidecimal numbers
2 $02
3 $04
4 $08
5 $10
6 $20
7 $40
8 $80
[/code]
To access a single bit use the AND:
[code]
i := $55 and $01; // i contains least significant bit
[/code]
To set a specific bit use the OR:
[code]
i := i or $02; // i second least significant bit is set
[/code]
Switching a bit:
[code]
i := i xor $01; // the least significant bit either cleared if set
// or set if it was cleared
[/code]
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.
[code]
i := i and ($FF-$08); // removes the 4th bit
[/code]