在C#中将单个hex字符转换为其字节值

这会将1个hex字符转换为整数值,但需要构造一个(子)字符串。

Convert.ToInt32(serializedString.Substring(0,1), 16); 

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

 int value = "0123456789ABCDEF".IndexOf(char.ToUpper(sourceString[index])); 

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

 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'); } 

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

 Convert.ToByte(stringValue, 16); 

只要stringValue代表hex数字? 不是基本参数的重点吗?

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

当然,您可以获得hex值,而无需创建另一个字符串。 我不确定它会给你带来什么,表现明智,但既然你问过,这就是你要求的。

  public int FromHex(ref string hexcode, int index) { char c = hexcode[index]; switch (c) { case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'A': case 'a': return 0xa; case 'B': case 'b': return 0xb; case 'C': case 'c': return 0xc; case 'D': case 'd': return 0xd; case 'E': case 'e': return 0xe; case 'F': case 'f': return 0xf; case '0': default: return 0; } } } 

如果你知道hex值只是一个字节,那么只需转换为Int32然后再转换

 var b = (byte)(Convert.ToInt32(serializedString, 16)); 
 Encoding.UTF8.GetBytes( serializedString.ToCharArray(), 0, 1) 

更便宜的可能是:

 Encoding.UTF8.GetBytes( new char[]{ serializedString[0] }, 0, 1) 

这只会将有趣的char添加到char []而不是整个字符串。