# 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.
LVL 1
###### Who is Participating?

Commented:
try this, its working

Private Function ByteToBool(ByVal ByteVal As Byte) As String

Dim Index As Integer

For Index = 1 To 8
ByteToBool = IIf(ByteVal And 1, "1", "0") & ByteToBool
ByteVal = ByteVal / 2
Next

End Function

Good Luck
Schild
0

Commented:
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

0

Author Commented:
Thanks, Poddy and schild.
You saved my day!!!
0

Commented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.