Page 1 of 1
Displaying A Byte As A Bit String
Posted: 15 April 2011, 10:01 AM
by jburrow
I'm in the middle of debugging a data stream, using many 'debug.print cstrhex(byte)' type statements. Then I have to do hex arithmetic in my head to figure out which bits are on and which bits are off.
As I'm looking at bit values, I have been trying to find s statement like 'debug.print cstrbit(byte)', where the resulting output would be a series of 0's and 1's, but I'm not seeing anything obvious.
Are there any suggestions please?
Thanks, John Burrow
San Diego
Having fun, out of the sun
Re: Displaying A Byte As A Bit String
Posted: 15 April 2011, 14:34 PM
by dkinzer
jburrow wrote:Then I have to do hex arithmetic in my head to figure out which bits are on and which bits are off.
That is a good skill to have, by the way. Practice, practice, practice.
jburrow wrote:I have been trying to find s statement like 'debug.print cstrbit(byte)'
There isn't any such function in the ZBasic System Library. Such a function is easy to create, however. The code below will work for a Byte value.
Code: Select all
'
'' CStrBits
'
' Convert a byte to a string of eight characters giving the binary
' representation of the value.
'
Function CStrBits(ByVal val as Byte) as String
Dim data(1 to 8) as Byte
Dim i as Integer
Dim mask as Byte
mask = &H80
For i = 1 to 8
data(i) = IIF(CBool(val And Mask), Asc("0"), Asc("1"))
mask = Shr(mask, 1)
Next i
CStrBits = MakeString(data.DataAddress, 8)
End Function
Sub Main()
Dim s as String
s = CStrBits(&H5a)
Debug.Print s
End Sub
If you want the same functionality for other data types you can use the overload capability to create like-named functions with a different parameter list.