[RESOLVED] Read / Write Bit Operations
Hello,
I'm not good with Bit/Byte operations & I'm looking for a solution.
I need to be able to read/modify/save bits from a byte.
For instance, the read the 2nd bit and change it to either 0 or 1 and then the whole thing back out to as a byte.
Any ideas?
Currently, I can already Read the Bits, but haven't figured out how to modify & resave out.
Re: Read / Write Bit Operations
The 1st bit of a byte is 2^0, 2nd bit is 2^1, 3rd is 2^2, 4th is 2^3, etc
Another way to look at it is that 1st bit is 1, 2nd bit is 2, 3rd bit is 4, 4th is 8, etc, doubling as you extend.
So 2nd bit (2^1) of a byte....
To return it: Value And 2
To set it: Value Or 2 and to clear it: Value And Not 2
To toggle it: Value Xor 2
For the 3rd bit (2^2)...
To return it: Value And 4
To set it: Value Or 4 and to clear it: Value And Not 4
To toggle it: Value Xor 4
Re: Read / Write Bit Operations
I've been testing but something doesn't quite seem right I think because bit 2 is actually pos 6
So here is the scenario: The byte in question is for instance: 68 | 0, 1, 0, 0, 0, 1, 0, 0,
So to read it would it be: debug.print 68 And 64 ?
Re: Read / Write Bit Operations
The location of the bits is done from right to left.
A Long has 32 bits, an Integer has 16 bits and a Byte has 8 bits, the get the same values you have to start at the right.
Otherwise you would never now which value "0010" would be.
Re: Read / Write Bit Operations
As mentioned, bits when printed out as 1's,0's are usually read right to left.
Another thing you may want to do is to create a look up array to help out (until you are comfortable).
Code:
Dim potLUT(1 to 32) As Long ' potLUT = power-of-twos lookup table
...
potLUT(1) = 1
For p = 2 to 31
potLUT(p) = potLUT(p - 1) * 2
Next
potLUT(p) = &H80000000
Now you can use your array, something like: Debug.Print lValue And potLUT(3) to test 3rd bit. Use zero-bound array if more comfortable with that
Shifting bits is a touch more challenging only because dealing with the high bit in a long/integer may be in play. But that is a slightly different topic than what you are asking here.
Re: Read / Write Bit Operations
Oh and another thing we didn't touch on. How to test for multiple bits being set... You OR together the bits to test like so:
Test 1st & 2nd bit (bit 0 & bit 1): If lValue And (1 Or 2) <> 0 Then one or both bits are set.
If the return value = (1 Or 2) then both bits are set
Re: Read / Write Bit Operations
Perfect. Got it working now. Thanks