excel vba long to binary string code example
Example 1: excel vba convert number to binary string
'VBA function to convert number to binary string:
Function DecToBin$(ByVal n&)
Do
DecToBin = n Mod 2 & DecToBin
n = n \ 2
Loop While n
End Function
'-------------------------------------------------------------------
'NB: Excel has the built-in worksheet function, DEC2BIN(), but it
'can only handle 10-bit numbers or less. The above function can
'convert all positive 32-bit numbers:
MsgBox DecToBin(9512489) '<--displays: 100100010010011000101001
Example 2: excel vba binary from long integer value
Function LongToBits$(ByVal n&)
Dim i&
LongToBits = "00000000000000000000000000000000"
If n And &H80000000 Then
Mid$(LongToBits, 1, 1) = "1"
n = n And Not &H80000000
End If
For i = 32 To 2 Step -1
If n And 1 Then Mid$(LongToBits, i, 1) = "1"
n = n \ 2
Next
End Function
'------------------------------------------------------------------------------
MsgBox ByteToBits(0) '<--displays: 00000000000000000000000000000000
MsgBox LongToBits(293781237) '<--displays: 00010001100000101011111011110101
MsgBox ByteToBits(-1) '<--displays: 11111111111111111111111111111111