含转换为十六进制值开始"的字符串; 0X"为整数或长 [英] Convert a string containing a hexadecimal value starting with "0x" to an integer or long
问题描述
我如何转换,如0x310530的字符串值,在C#中?
我试过的 int.TryParse 的整数值(连的 int.TryParse 的用的 System.Globalization.NumberStyles.Any 的),但它不工作。
更新:
似乎无需移除尾随0XConvert.ToInt64或Convert.ToInt32工作:
长HWND = Convert.ToInt64(0x310530,16);
的文档 Convert.ToInt64方法(String,Int32)将
说:
如果fromBase是16,你可以前缀由值
参数与指定的数字 0x或0X。
块引用>
不过,我宁愿喜欢的TryParse方法,它不会引发异常。
解决方案int值=(int)的新System.ComponentModel.Int32Converter()。ConvertFromString(0x310530 );
How can I convert a string value like "0x310530" to an integer value in C#?
I've tried int.TryParse (and even int.TryParse with System.Globalization.NumberStyles.Any) but it does not work.
UPDATE: It seems that Convert.ToInt64 or Convert.ToInt32 work without having to remove the trailing "0x":
long hwnd = Convert.ToInt64("0x310530", 16);
The documentation of
Convert.ToInt64 Method (String, Int32)
says:"If fromBase is 16, you can prefix the number specified by the value parameter with "0x" or "0X"."
However, I would prefer a method like TryParse that does not raise exceptions.
解决方案int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530");
这篇关于含转换为十六进制值开始"的字符串; 0X"为整数或长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!