我在窗體上有一個文本框。我想寫「0x31」作爲字符串到我的文本框,然後當我點擊一個按鈕,我想將這個字符串轉換爲0x31作爲十六進制值。在C中將十六進制字符串轉換爲其數值#
我怎麼能轉換這個字符串十六進制值?
我在窗體上有一個文本框。我想寫「0x31」作爲字符串到我的文本框,然後當我點擊一個按鈕,我想將這個字符串轉換爲0x31作爲十六進制值。在C中將十六進制字符串轉換爲其數值#
我怎麼能轉換這個字符串十六進制值?
string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
// Get the character corresponding to the integral value.
string stringValue = Char.ConvertFromUtf32(value);
char charValue = (char)value;
Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
hex, value, stringValue, charValue);
}
int i = Convert.ToInt32("0x31", 16);
Console.WriteLine("0x" + i.ToString("X2"))
十六進制只是一個值的表示,它本身並不是一個值。
本頁面會告訴你,你需要知道在C#解析和顯示六角一切
字符串十六進制值的表示值。實際的字符串值可以轉換爲任何你喜歡的(float,int等) 有幾種方法可以做the conversion。簡單的例子:
// convert to int from base 16
int value = Convert.ToInt32(hex, 16);
首先清理:字符串是十六進制格式,當你將其轉換爲一個數值,它只是一個數值,它不是十六進制。
使用Int32.Parse
方法與NumberStyle.HexNumber
符:
string input = "0x31";
int n;
if (input.StartsWith("0x")) {
n = Int32.Parse(input.Substring(2), NumberStyles.HexNumber);
} else {
n = Int32.Parse(input);
}
注意,十六進制是一個值的只是一種表象 - 所以你真正問的是你如何解析從字符串的值 - 做像這樣:
int val = int.Parse("0x31", NumberStyles.HexNumber);
val現在包含一個int值和十六進制值0x31。