【发布时间】:2017-06-17 05:42:41
【问题描述】:
这个问题看起来像一堆其他问题,但没有一个完全符合我的需要。其他相关问题的问题似乎是基于 Visual Studio 的 IntelliSense 隐式转换为十进制。
目标:尝试在 C# 中将十六进制字符串转换为十六进制值(不是十进制值)的字节数组。
public static byte[] ConvertHexValueToByteArray()
{
string hexIpAddress = "0A010248"; // 10.1.2.72 => "0A010248"
byte[] bytes = new byte[hexIpAddress.Length / 2];
for (int i = 0; i < hexIpAddress.Length; i += 2)
{
string s2CharSubStr = hexIpAddress.Substring(i, 2); // holds "0A" on 1st pass, "01" on 2nd pass, etc.
if ((s2CharSubStr.IsAllDigit()) && (int.Parse(s2CharSubStr) < 10)) // fixes 0 to 9
bytes[i / 2] = (byte) int.Parse(s2CharSubStr); // same value even if translated to decimal
else if (s2CharSubStr.IsAllDigit()) // fixes stuff like 72 (decimal) 48 (hex)
bytes[i / 2] = Convert.ToByte(s2CharSubStr, 10); // does not convert, so 48 hex stays 48 hex. But will not handle letters.
else if (s2CharSubStr[0] == '0') // handles things like 10 (decimal) 0A (hex)
bytes[i / 2] = // ?????????????????????????????
else // handle things like AA to FF (hex)
bytes[i / 2] = // ?????????????????????????????
}
return bytes;
}
像下面两个这样的答案执行从十六进制到十进制的隐式转换(如在 Visual Studio 的 IntelliSense 中所见)和/或无法处理十六进制的 alpha 部分: 1)
bytes[i / 2] = (byte)int.Parse(sSubStr, NumberStyles.AllowHexSpecifier);
2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
3) bytes[i / 2] = Convert.ToByte(hexIpAddress.Substring(i, 2));
所以我希望函数返回这个硬编码字节数组的等价物:
byte[] currentIpBytes = {0x0A, 01, 02, 0x48};
【问题讨论】:
-
“十进制”和“十六进制值”有什么区别?它们是字节,0x01 与 1 相同,0x0a 与 10 相同,以此类推,当您处理二进制数据而不是字符串数据时,表示与底层数据无关。
-
但是 2) 是正确的。
byte值是byte值...所以bytes[0]的值将是10(十进制),是0x0A。您还希望bytes[0]具有什么其他价值? -
我希望函数返回这个硬编码字节数组的等价物:byte[] currentIpBytes = {0x0A, 01, 02, 48};
-
是的,所以
bytes[i/2] = Convert.ToByte(hexIpAddress.Substring(i,2));完全符合您的要求。 (虽然是0x48,而不是48) -
@Rene, public static byte[] ConvertHexValueToByteArray() { string hexIpAddress = "0A010248"; byte[] bytes = new byte[hexIpAddress.Length / 2]; for (int i = 0; i