Parsing hex values from strings.

wyrd

Senior Contributor
Joined
Aug 23, 2002
Messages
1,405
Location
California
How can I parse a hex string into an integer value?

Example.

You can this for hex values:
int i = 0x00112233;

But this throws an error:
string str = "0x00112233";
int i = int.Parse(str);

Any ideas? Thanks in advance.

Update:
I've tried using \x00112233 instead, and also (int) and Convert.ToInt32 for conversions (for both type of string values). Nothing has yet to work.
 
Last edited:
Found solution:

Had to change 0x00112233 to 00112233 and then use System.Globalization.NumberStyles.HexNumber:

string str = "00112233";
int i = int.Parse(str, System.Globalization.NumberStyles.HexNumber);
 
have you tried replacing the 0x parts with &H ? eg:
Visual Basic:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '/// try replacing the 0x with &H
        Dim x As Integer = (&H112233) '/// the 2 zeros will disappear
        '/// or as a string
        Dim s As String = "&H00112233" '/// same as &H112233
        Dim i As Integer = s '/// no need to Parse.
        '/// check the values returned...
        MessageBox.Show("the integer x looks like this >>> " & x & Environment.NewLine & "  the integer i looks like this >>> " & i)

    End Sub
 
Hmm.. didn't try that, no. I'll stick with what I have, it's more clear on what the code is doing and self documenting (as the actual hex value is in a file, not in the code). Thanks anyway though.
 
Back
Top