I have experimented with various ways of extracting a bit (at a specified position) from a byte, and have come up with a slightly convoluted way of doing this as follows:
The b And PowerOf2(k) returns 0 if the k bit is not set, and 2^k if it is set.
The CBool then coverts this to False (value 0) or True (value -1) respectively.
Finally, the leading minus sign converts the Boolean into the required value of 0 (unset) or 1 (set).
In massive loops, -CBool(b And PowerOf2(k)) has proved to be faster than using anything else I have tried. (For example, testing If b And PowerOf2(k) > 0 is considerably slower.) But it looks a bit weird (no pun intended...), and I can't help but think there's probably a faster and more natural way. Is there?
Also, can a variable be defined as a bit rather than a byte? I don't want to use Boolean, since I shall be using the bits in numerical calculations.
VBA Code:
Sub Test()
Dim PowerOf2(0 To 7) As Byte 'Store powers of 2 for efficiency
Dim b As Byte
Dim ExtractedBit(0 To 7) As Byte 'Really a bit array: only takes values 0 or 1
Dim k As Long 'Bit counter
'This loop allows powers of 2 to be calculated only once at the start.
'Referring to PowerOf2(5) thousands of times in a big loop is faster than calculating 2^5 each time.
For k = 0 To 7
PowerOf2(k) = 2 ^ k
Next k
b = 173
For k = 0 To 7
'Extract kth bit, where bits are numbered 0 to 7 (right to left)
ExtractedBit(k) = -CBool(b And PowerOf2(k))
Debug.Print ExtractedBit(k)
Next k
End Sub
The b And PowerOf2(k) returns 0 if the k bit is not set, and 2^k if it is set.
The CBool then coverts this to False (value 0) or True (value -1) respectively.
Finally, the leading minus sign converts the Boolean into the required value of 0 (unset) or 1 (set).
In massive loops, -CBool(b And PowerOf2(k)) has proved to be faster than using anything else I have tried. (For example, testing If b And PowerOf2(k) > 0 is considerably slower.) But it looks a bit weird (no pun intended...), and I can't help but think there's probably a faster and more natural way. Is there?
Also, can a variable be defined as a bit rather than a byte? I don't want to use Boolean, since I shall be using the bits in numerical calculations.