Link to home
Start Free TrialLog in
Avatar of rakkas
rakkas

asked on

Pulling out '0' and '1' from a byte

Is there a easy way of telling what bit's are set in a byte?
Can someone please give me an example of a function that takes a byte (0-255) as input and leaves perhaps a string containing 8 chars i.e "00101101" as a result?
I need to test if certain bit's are set, for example value 4 (the third from the right) ignoring other bit's that are set.
ASKER CERTIFIED SOLUTION
Avatar of schild
schild

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Poddy
Poddy

I would recommed using the And operator.

To test for bits being set, take the decimal value of the bit, and AND it against the tested value.

If it is set it will return the value that you are testing for, if not, it will return zero

Bracket the AND expression or you may get strange results (AND has lower priority than =)

So

(7 and 4)  = 4
(8 and 4)  = 0

etc



Avatar of rakkas

ASKER

Thanks, Poddy and schild.
You saved my day!!!
The above doesnt seems to work with some numbers. Take 100 for example. I've modified it a bit into the following code. Thanks for your code though, schild.

Public Function ByteToBin(ByVal ByteVal As Byte) As String
Dim Index As Integer

For Index = 1 To 8
    ByteToBin = IIf(ByteVal Mod 2, "1", "0") & ByteToBin
    ByteVal = ByteVal \ 2
Next
End Function