How to parse decimal and hexadecimal string depending on number format to int

Viewed 399

How do I parse a string with either a decimal number like 1234 or hexadecimal number prefixed with 0X1234 to an int in C#?

I have tried int.TryParseand Convert.ToInt32 But it seems like these function assumes that you know if you want to parse a decimal or a hexidecimal value on prehand. I want to allow my user to input both formats.

Are there any standard functions that can decide by them selves if the input is formatted in hex or decimal format? Or do I have to write it myself?

2 Answers

You can use the following code:

int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString(hexString);

where hexString can be 0x1234 and 1234. It handles hex and non hex cases.

Not sure about one unique method. But why not use conditional operator?

string input = "0xA3";
int result = input.Contains("0x") ? Convert.ToInt32(input , 16) : Convert.ToInt32(input);
Related