Jump to content
Xtreme .Net Talk

Recommended Posts

Posted (edited)

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.

Edited by wyrd
Gamer extraordinaire. Programmer wannabe.
Posted

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);

Gamer extraordinaire. Programmer wannabe.
  • *Experts*
Posted

You can also use Convert.ToInt32(str, 16). The 16 is the "fromBase" parameter, 16 for hex.

 

-Ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
  • Leaders
Posted

have you tried replacing the 0x parts with &H ? eg:

   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

Posted
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.
Gamer extraordinaire. Programmer wannabe.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...