情景:
我有二进制数据。我的要求是我需要一个按以下顺序包含的输出字节数组:
请帮帮我。
答案 0 :(得分:1)
提供问题中的二进制数据实际上是数组:
Byte[] binaryData = new Byte[] {
0x12, 0x13, 0x14, 0x15
};
Byte[] result = Enumerable
.Range(0, binaryData.Length / 2)
.Select(index => unchecked(BitConverter.ToInt16(binaryData, index * 2)))
//.Select(item => (Int16) unchecked((item << 8) | (item >> 8))) // if you want to swap the endians
.Select(value => (Int16) unchecked(~value + 1))
.SelectMany(value => unchecked(new Byte[] {(Byte) (value >> 8), (Byte) (value & 0xFF)}))
.ToArray();
// Test
// "ec, ee, ea, ec"
// ("ed, ed, eb, eb" when endians are swapped)
Console.Write(String.Join(", ", result.Select(item => item.ToString("x2"))));
编辑:如果(请参阅注释)应更改每个字节(不是 2字节字):
Byte[] binaryData = new Byte[] {
224, 46
};
Byte[] result = binaryData
.Select(b => unchecked((Byte) (~b + 1)))
.ToArray();
// "20 D2"
Console.Write(String.Join(", ", result.Select(item => item.ToString("x2"))));