I've been trying to find a decimal to binary and binary to decimal function that works correctly with negative numbers, but so far, none have held up to the challenge. I want this to work in Visual Basic, but the VB code will eventually be ported to ASP, so I would rather avoid using external components.
For example, I am reading a Long value from a file. This value is negative, eg, -1487631. When I attempt to convert this to binary using the following function, I of course get a 0 since the function only does positive numbers.
If I try to read the Long as 4 bytes, then convert each byte into an 8 bit binary string, and concatate the 4 strings together, then try to convert the binary string back to a long, I get a number like 1487630.
My question is, how exactly are 4 byte negative longs (or 2 byte negative integers, etc) stored in either files or memory? What's the best way to correctly convert from a negative or positive number of an arbitrary byte length (anything from 1 byte to 32 bytes, even odd ones such as 5, 17, etc)?
Here are the functions I'm currently using.
Public Function Dec2Bin(ByVal Num As Variant) As String
Dim x As Integer
For x = 100 To 0 Step -1 ' I don't expect to ever use a number bigger than (2 ^ 100)
If Num >= (2 ^ x) Then
' Stop
Dec2Bin = Dec2Bin & "1"
Num = Num - (2 ^ x)
Else
Dec2Bin = Dec2Bin & "0"
End If
Next x
Do While Left(Dec2Bin, 1) = "0"
Dec2Bin = Mid(Dec2Bin, 2) ' Remove all extra 0's from the front.
Loop
Do Until Len(Dec2Bin) Mod 8 = 0 And Len(Dec2Bin) <> 0 ' Make sure there are 8 'bits' returned
Dec2Bin = "0" & Dec2Bin
Loop
End Function
Public Function Bin2Dec(ByVal Bin As String) As Variant
Dim x As Integer
For x = 1 To Len(Bin)
Bin2Dec = Bin2Dec + Int(Mid(StrReverse(Bin), x, 1) * (2 ^ (x - 1)))
Next x
End Function
Current points set at 250, but I'm willing to increase it for a prompt response, or information that goes above and beyond what I've asked for.
James
Public Function Bin2Dec(Bin as string) as Long
Dim x as integer
for x = 1 to len(bin)
Bin2Dec = Bin2Dec OR Int(Mid(StrReverse(Bin), x, 1) * (2 ^ (x - 1)))
next
End Function
Public Function Dec2Bin(Dec as Long) as String
Dim x as integer
for x = 1 to 32
Dec2Bin = iif(mid(dec,x,1) = "1",1,0)*(2^(32-x))
next
End Function
That's all freehand, so there might be some glitches, but hopefully you get the idea.
Zaphod.