开发者

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 s开发者_JAVA百科uch as 0x7c or 0x777 but I keep getting errors?

Thanks.


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


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


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜