Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c# - Convert a string containing a hexadecimal value starting with "0x" to an integer or long

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 leading "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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
int value = (int)new System.ComponentModel.Int32Converter().ConvertFromString("0x310530");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...