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

时间:2017-01-31 17:10:14

标签: c# arrays hex

这个问题看起来像是一堆其他问题,但没有一个完全符合我的需要。其他相关问题的问题似乎是基于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的智能感知中查看)和/或无法处理十六进制的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};

1 个答案:

答案 0 :(得分:1)

string hexIpAddress = "0A010248"; // 10.1.2.72 => "0A010248"
byte[] bytes = new byte[hexIpAddress.Length / 2];

for (int i = 0; i < hexIpAddress.Length; i += 2)
    bytes[i/2] = Convert.ToByte(hexIpAddress.Substring(i, 2), 16);

这导致这个数组:

bytes = {0x0A, 0x01, 0x02, 0x48}; 

或表示为小数:

bytes = {10, 1, 2, 72};

或二进制文件000010100000000010000001001001000(C#6中仍不支持二进制文字)。

值相同byte中的任何基础都没有表示。您只能决定在将它们再次转换为字符串时如何表示值:

foreach(byte b in bytes)
    Console.WriteLine("{0} {0:X}", b);

结果

10 A
1 1
2 2
72 48