Hello David
On Sunday, 8 March 1998 19:18:00, you wrote to All:
DR> How do can I read the individual bits that are inside a byte?
By means of the AND operator. Say you want to test if the third bit from
the right, beginning with number 0, of an integer variable Var% is set.
First you make an integer value in which only the third bit is set: that
is 2^3 = 8. Then you apply the AND operator on both values:
Check% = (Var% AND 8)
Now if Check% has the value 8 the third bit of Var% set, and if it has
the value 0 the third bit is not set.
Tests of the other bits are analogous. For instance, to test for the
fifth bit you have to AND the variable with 2^5 = 32. Generally it will
be more efficient to calculate the powers of 2 beforehand and to place
them in an array:
CONST HiBit% = 7
DIM Power2%(HiBit%)
Power2%(0) = 1
FOR i% = 2 TO HiBit%
Power2%(i%) = Power2%(i%) * 2
NEXT i%
For testing the bits of whole integers you set HiBit% = 15, and for
long integers HiBit% = 31. A test of the i%th bit goes as follows:
IthBitSet = (Var% AND Power2%(i%)) > 0
IthBitSet will be -1 (TRUE) if the i%th bit is set, and 0 (FALSE)
otherwise.
If you want to have the value 0 or 1 as a result you simply divide Var%
by the right power of 2:
IthBit% = Var% \ Power2%(i%)
Friendly greeting you,
Hans Lunsing, Fido : 2:500/104.6955
Internet : jlunsing@doge.nl
--- Terminate 5.00/Pro
---------------
* Origin: HCC DOSgg SW Boss West 1, ++31793317774 (2:500/104.6955)
|