0

I want to convert 000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717 hex value to it's binary format (to a string of binary), but following code throws an exception if either value being too big or too small. Why is that?

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim binstring As String
        Dim hexstring As String = "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717"
        binstring = Convert.ToString(Convert.ToInt32(hexstring, 16), 2)

        T5.Text = binstring
    End Sub
1
  • 1
    Your code includes this expression Convert.ToInt32(hexstring, 16) which tries to convert your hex string to a 32-bit integer. The string in your example converts to a number that is far more than 32 bits. Commented Jun 18, 2016 at 14:46

2 Answers 2

1

Convert.ToInt32 converts to, unsurprisingly, an Int32.

The maximum value of an Int32 is Int32.MaxValue, which is 2,147,483,647.

The number in your code, 0x117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717, is much larger than that (6,860,217,587,554,922,525,607,992,740,653,361,396,256,930,700,588,249,487,127 in decimal), so it doesn't come close to fitting.

EDIT

You didn't ask for help actually converting this, but here's a hint: each hex digit represents four binary digits (because 16 is 2^4). You can convert each digit of the hexadecimal individually and just concatenate them. In other words, 0xF1 = 11110001 in binary, because 0xF = 1111 and 0x1 = 0001. Just be careful to keep the trailing zeros you need.

Sign up to request clarification or add additional context in comments.

Comments

1

As I said in my comment on your question, your hex string is too long to convert to a 32-bit integer, which your code is trying to do. I would approach this by looping through the characters of the hex string and converting each to a binary string of length 4 (padded on the left with "0").

Dim hexstring As String = "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717"
Dim bin As New Text.StringBuilder
For Each ch As Char In hexstring
    bin.Append(Convert.ToString(Convert.ToInt32(ch, 16), 2).PadLeft(4, "0"c))
Next
T5.Text = bin.ToString

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.