c# - 如何在 C# 中从字节和半字节构建字节数组
问题描述
给定字符串数组的这种结构
string[] content = {"0x1", "5", "0x8", "7", "0x66"};
如何获得content
等效的字节数组表示?0x1
我知道如何转换“5”、“7”和“0x66”,但我正在努力在数组中构建半字节的整个字节数组表示0x8
......基本上我不知道如何连接“ 0x1"
, "5"
,"0x8"
到两个字节...
附加信息:字符串数组的序列仅包含字节或半字节数据。前缀“0x”和一个数字被解释为半字节,没有前缀的数字应该被解释为字节,带有两个数字的十六进制字符串应该被解释为字节。
解决方案
如果所有项目都应该是十六进制,Linq和Convert
就足够了:
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
推荐阅读
- javascript - 在 iframe 中设置交叉原点变量
- java - TabLayout 中 Fragment 的 onStop 以保存一些内容
- python - 创建平滑的跳跃动画
- laravel - 通过 mailgun 发送电子邮件时,此路由不支持 GET 方法
- javascript - 如何使网站按价格从大到小排序
- python - ImportError:无法从“预处理”导入名称“inception_preprocessing”
- pagination - 对集合使用分页时出现 Jekyll 布局错误 (jekyll-paginate-v2)
- json - 尝试通过 Compass 将 JSON 文件导入 MongoDB 时出现错误
- django - 为什么变量不能与 Django 信号中的“实例”一起使用?
- nginx - nginx 总是在域后添加斜杠