在C#中将单个十六进制字符转换为其字节值

nos*_*nos 4 .net c# hex

这会将1个十六进制字符转换为其整数值,但需要构造一个(子)字符串.

Convert.ToInt32(serializedString.Substring(0,1), 16);
Run Code Online (Sandbox Code Playgroud)

.NET是否有内置的方法将单个十六进制字符转换为不涉及创建新字符串的字节(或int,无关紧要)值?

Ben*_*n M 16

int value = "0123456789ABCDEF".IndexOf(char.ToUpper(sourceString[index]));
Run Code Online (Sandbox Code Playgroud)

甚至更快(减法与阵列搜索),但不检查错误输入:

int HexToInt(char hexChar)
{
    hexChar = char.ToUpper(hexChar);  // may not be necessary

    return (int)hexChar < (int)'A' ?
        ((int)hexChar - (int)'0') :
        10 + ((int)hexChar - (int)'A');
}
Run Code Online (Sandbox Code Playgroud)


alm*_*ori 16

纠正我,如果我错了,你可以简单地使用

Convert.ToByte(stringValue, 16);
Run Code Online (Sandbox Code Playgroud)

只要stringValue代表十六进制数字?不是基本参数的重点吗?

字符串是不可变的,我不认为有一种方法可以在索引0处获取char的子字符串字节值而无需创建新字符串