Displaying A Byte As A Bit String

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
jburrow
Posts: 11
Joined: 03 January 2011, 15:27 PM

Displaying A Byte As A Bit String

Post 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
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: Displaying A Byte As A Bit String

Post 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.
- Don Kinzer
Post Reply