flavour404
flavour404

Reputation: 6312

converting string to uint

I am trying to read in a hex value from a text box and then put it in a uint, this is the code:

UInt32 x = Convert.ToUInt32(location_txtbox.ToString());

Why, I want to pass x to some unmanaged code and the function header requires a DWORD.

I'm getting an 'input string was not in correct format error? I am trying to input values such as 0x7c or 0x777 but I keep getting errors?

Thanks.

Upvotes: 4

Views: 16321

Answers (4)

ernestpazera
ernestpazera

Reputation: 21

A) Never use Convert without wrapping it in a try/catch, or unless you are VERY sure that what you are parsing will be parsed successfully.

B) Use uint.TryParse. In particular, use the one that allows you to specify the number style. The reference for it is at http://msdn.microsoft.com/en-us/library/kadka85s.aspx

C) in the style it appears that you will need NumberStyles.HexSpecifier

D) Use the Text property, as stated above.

Upvotes: 2

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234444

Convert.ToUInt32 just calls UInt32.Parse(String). If you call the overload that takes a NumberStyles parameter, you can specify your value is hexadecimal. Trouble is, you'll have to cut out the leading "0x", as it isn't allowed.

var hexNumber = "0x777".Substring(2);
uint.Parse(hexNumber, System.Globalization.NumberStyles.HexNumber)

Upvotes: 2

Jeff Mercado
Jeff Mercado

Reputation: 134841

Use this overload of Convert.ToUInt32 where you specify the base of the conversion. It should work with or without the leading "0x".

UInt32 x = Convert.ToUInt32(location_txtbox.Text, 16);

Upvotes: 14

Andy Lowry
Andy Lowry

Reputation: 1773

Assuming location_txtbox is a TextBox, you may want to use .Text instead of .ToString().

And I think you need to pass 16 as the second parameter to parse hex: e.g. Convert.UInt32( X, 16)

See: http://msdn.microsoft.com/en-us/library/swz6z5ks.aspx

Upvotes: 3

Related Questions