• Status: Solved
• Priority: Medium
• Security: Public
• Views: 440

# 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
• 2
1 Solution

Commented:
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

Commented:
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

Commented:
"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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.