I frequently use bits in numeric variables as flags. During testing and debugging, I sometimes need to know which bits are set or cleared. Debug.Print or mousing over the variable while execution is paused is fine if I'm only using a few bits, but when the number of flag bits gets large, decoding the displayed value is a monumental PIA.
I've written a small function that shows the bits. No big deal, anyone can do that, but I've added a formatting option.
The function takes two parameters – the flag variable and an optional mask string. If the mask is not supplied, the function spits back a string broken into bytes. But sometimes I have things like three bits for one related set of conditions, then two more for another set, then five, then one, and so on. In such a case, it is more helpful to me to see the breaks between the related groups, rather then arbitrarily on byte boundaries.
The mask string looks for spaces. When there is a non-space, it outputs a one or zero for the bit value. When there is a space, it adds a space in the corresponding position of the output string. When there is a mask, it will generate a string at least as long as the mask, longer if necessary to show all set bits. When the mask is shorter than the generated string, it packs all the remaining bits together.
When there is no mask, the function stops when it runs out of set bits.
This is a programmer's debugging tool, so there is no provision for gracefully handling problems, but I see very little likelihood that displaying a bit pattern would ever be used in production anyway.
Code:
Public Function ShowBits$(ByVal hodnota&, Optional ByVal maska$)
Dim i&, m&, l&, JeMaska As Boolean
l = Len(maska)
JeMaska = l > 0
m = 1
Do
If CBool(hodnota And m) = True Then
ShowBits = "1" & ShowBits
Else
ShowBits = "0" & ShowBits
End If
m = m * 2
i = i + 1
If (m > hodnota) And ((JeMaska = False) Or ((JeMaska = True) And (i >= l))) Then Exit Function
If (l > 0) Then
If (l > i) Then
If Mid$(maska, l - i, 1) = " " Then
ShowBits = " " & ShowBits
i = i + 1
End If
End If
Else
If (i Mod 4) = 0 Then ShowBits = " " & ShowBits
End If
Loop
End Function