将十六进制字符串转换为C#中的数值

san*_*p22 2 c# string hex

我的表格上有一个文本框.我想将"0x31"作为字符串写入我的文本框,然后当我单击一个按钮时,我想将此字符串转换为0x31作为十六进制值.

如何将此字符串转换为十六进制值?

L.B*_*L.B 6

int i = Convert.ToInt32("0x31", 16);
Console.WriteLine("0x" + i.ToString("X2"))
Run Code Online (Sandbox Code Playgroud)


小智 5

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);
}
Run Code Online (Sandbox Code Playgroud)

示例来自:http : //msdn.microsoft.com/en-us/library/bb311038.aspx


Guf*_*ffa 5

首先要澄清的是:字符串是十六进制格式,当您将其转换为值时,它只是一个数值,而不是十六进制。

使用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);
}
Run Code Online (Sandbox Code Playgroud)