Parsing hex values from strings.

wyrd

Well-known member
Joined
Aug 23, 2002
Messages
1,408
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:
Ive 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 by a moderator:
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:
Code:
    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.. didnt try that, no. Ill stick with what I have, its 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