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
Dec2Bin = Dec2Bin & "1"
Num = Num - (2 ^ x)
Dec2Bin = Dec2Bin & "0"
Do While Left(Dec2Bin, 1) = "0"
Dec2Bin = Mid(Dec2Bin, 2) ' Remove all extra 0's from the front.
Do Until Len(Dec2Bin) Mod 8 = 0 And Len(Dec2Bin) <> 0 ' Make sure there are 8 'bits' returned
Dec2Bin = "0" & Dec2Bin
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)))
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.