1

I need to take a vendor ID from a user in the form of an int32, and they usually look something like this. 0x0EB8 I can write this as code

    int32 vid = 0x0EB8;

That works just fine. But I need to get it from the user in the form of a string. And when I call System.Convert.ToInt32("0x0EB8") I get a Type Conversion Exception.

here is some of my test code that gives me the exception.

        Int32 blah;
        Console.WriteLine("Please enter the Vendor ID");
        string blahString = Console.ReadLine();
        blah = Convert.ToInt32(blahString);

Anyone know a good way to do this??

dcp
  • 54,410
  • 22
  • 144
  • 164
BurntCandy
  • 55
  • 1
  • 9

2 Answers2

5

You can pass in the radix as second parameter.

int blah = Convert.ToInt32(blahString, 16);
dcp
  • 54,410
  • 22
  • 144
  • 164
  • See [MSDN documentation](http://msdn.microsoft.com/en-us/library/1k20k614.aspx) for more information. – JDB Mar 06 '14 at 18:22
2

You can give a look at MSDN's How to: Convert Between Hexadecimal Strings and Numeric Types to learn how to convert hexadecimal to numeric types.

A sample from that article:

Note: you need to drop the '0x' from your original hexadecimal string

string hexString = "0EB8";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
SlashJ
  • 687
  • 1
  • 11
  • 31
  • Checked that out and it helped alot. I was looking around the MSDN for thew convert class but that was of no help the hex page helped. – BurntCandy Mar 06 '14 at 18:40