• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 436
  • Last Modified:

String-Bin-Dec

I have a String = 11001101 or CD

How can I ...
i) cast the string to Bin/Hex?
ii) get the value of Dec for the Bin and Hex?

TQ;
0
pkimk
Asked:
pkimk
  • 2
1 Solution
 
TchalkovCommented:
Private Function BinToDec(str As String) As String
    If Len(str) = 0 Then
        BinToDec = 0
        Exit Function
    End If
    Dim i As Integer
    Dim d As Long
    Dim l As Integer
    Dim rez As Long
    l = Len(str)
    d = 1
    For i = 1 To l
        If Mid(str, l + 1 - i, 1) = "1" Then
            Res = Res + d
        End If
        d = d * 2
    Next i
    BinToDec = CStr(Res)
End Function
0
 
caraf_gCommented:
Bin is a bit more work, but from Hex to Dec and vice versa is easy.

strHex = Hex(strDec)
strDec = cstr(val("&H" & strhex))

For Hex to Bin, make sure that len(strBin) is a multiple of four

For lngCounter = 1 to len(strBin) Step 4
    strDigit = Mid(strBin, lngCounter, 4)

Then translate strDigit according to the following table:

0000 - 0
0001 - 1
0010 - 2
....
1001 - 9
1010 - A
....
1111 - F

So, that allows you to convert a binary string to a hexadecimal. To convert to decimal, I suggest you convert to hex first.

If a binary string has a number of digits that is not a multiple of four, prefix with "0" until it is.

Hope this helps.
0
 
caraf_gCommented:
"For Hex to Bin, make sure that "

Oops, that should have been

"For Bin to Hex, make sure that "

Hex to Bin is easy, just process one character at a time and replace with four-character combination as per above table.

Dec to Bin, again, via Hex
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now