首页 > 解决方案 > 如何在 C# 中从字节和半字节构建字节数组

问题描述

给定字符串数组的这种结构

string[] content = {"0x1", "5", "0x8", "7", "0x66"};

如何获得content等效的字节数组表示?0x1我知道如何转换“5”、“7”和“0x66”,但我正在努力在数组中构建半字节的整个字节数组表示0x8......基本上我不知道如何连接“ 0x1", "5","0x8"到两个字节...

附加信息:字符串数组的序列仅包含字节或半字节数据。前缀“0x”和一个数字被解释为半字节,没有前缀的数字应该被解释为字节,带有两个数字的十六进制字符串应该被解释为字节。

标签: c#

解决方案


如果所有项目都应该是十六进制,LinqConvert就足够了:

string[] content = {"0x1", "5", "0x8", "7", "0x66"};

byte[] result = content
  .Select(item => Convert.ToByte(item, 16))
  .ToArray();

如果"5"and"7"应该是十进制的(因为它们不是从 开始0x),我们必须添加一个条件:

byte[] result = content
  .Select(item => Convert.ToByte(item, item.StartsWith("0x", StringComparison.OrdinalIgnoreCase) 
    ? 16
    : 10))
  .ToArray();

编辑:如果我们想组合 nibbles,让我们为它提取一个方法:

private static byte[] Nibbles(IEnumerable<string> data) {
  List<byte> list = new List<byte>();

  bool head = true;

  foreach (var item in data) {
    byte value = item.StartsWith("0x", StringComparison.OrdinalIgnoreCase) 
      ? Convert.ToByte(item, 16)
      : Convert.ToByte(item, 10);

    // Do we have a nibble? 
    // 0xDigit (Length = 3) or Digit (Length = 1) are supposed to be nibble
    if (item.Length == 3 || item.Length == 1) { // Nibble
      if (head)                                 // Head
        list.Add(Convert.ToByte(item, 16));
      else                                      // Tail
        list[list.Count - 1] = (byte)(list[list.Count - 1] * 16 + value);

      head = !head;
    }
    else { // Entire byte
      head = true;

      list.Add(value);
    }
  }

  return list.ToArray();
}

...

string[] content = { "0x1", "5", "0x8", "7", "0x66" };

Console.Write(string.Join(", ", Nibbles(content)
  .Select(item => $"0x{item:x2}").ToArray()));

结果:

// "0x1", "5" are combined into 0x15
// "0x8", "7" are combined into 0x87
// "0x66"  is treated as a byte 0x66
0x15, 0x87, 0x66

推荐阅读