C# - 如何将 4 位和 12 位放入 2 个字节
C# - how to put 4 bit and 12 bit into 2 bytes
我有 2 个 bytes
应该以这种方式填充:
第一个数字 (4b) 第二个数字 (12b)
所以4位可以在1-15之间
而12位可以在1-50之间
所以我有这个 Bytes Array
:
byte[] packetArrayBytes = new byte[Length];
我理解这个问题的方式是你有这两个(大概)无符号整数 a
和 b
:
(我会用十六进制写它们以便于阅读)
a: 0x0000000X
b: 0x00000XXX
其中 a
是 4 位数字,b
是 12 位数字,X
标记包含相关值的位。
您想将它们存储在两个单独的 8 位块中:c: 0x00
和 d: 0x00
因此您需要将位移动到位,如下所示:
byte[] packetArrayBytes = new byte[2];
uint intA = 0xF; // Allowed range is 0-15 (0x0-0xF)
uint intB = 0xABC; // Allowed range is 0-4095 (0x0-0xFFF)
// Need to convert from uint to bytes:
byte[] bytesA = BitConverter.GetBytes(intA);
byte[] bytesB = BitConverter.GetBytes(intB);
byte a = bytesA[0]; // a is 0x0F
byte b = bytesB[1]; // b is 0x0A
int c = 0x00; // c is 0x00
int d = bytesB[0]; // d is 0xBC
// Mask out 4 least significant bits of a,
// then shift 4 bits left to place them in the most significant bits (of the byte),
// then OR them into c.
c |= (a & 0x0F) << 4; // c is now 0xF0
// Mask out 4 least significant bits of b,
// then OR them into c.
c |= b & 0x0F; // c is now 0xFA
packetArrayBytes[0] = (Byte)c;
packetArrayBytes[1] = (Byte)d;
Console.WriteLine(BitConverter.ToString(packetArrayBytes)); // Prints "FA-BC"
完成这些操作后,a
和 b
的值应该像这样放在字节 c
和 d
中:
c: 0xFA
d: 0xBC
。然后您可以将其放入数组中。
要取回这些值,只需反向执行这些相同的操作即可。
如果 a
和 b
是有符号值,我相信相同的操作有效,但您必须确保在将数据读回时没有将它们解释为无符号数字。
我有 2 个 bytes
应该以这种方式填充:
第一个数字 (4b) 第二个数字 (12b)
所以4位可以在1-15之间 而12位可以在1-50之间
所以我有这个 Bytes Array
:
byte[] packetArrayBytes = new byte[Length];
我理解这个问题的方式是你有这两个(大概)无符号整数 a
和 b
:
(我会用十六进制写它们以便于阅读)
a: 0x0000000X
b: 0x00000XXX
其中 a
是 4 位数字,b
是 12 位数字,X
标记包含相关值的位。
您想将它们存储在两个单独的 8 位块中:c: 0x00
和 d: 0x00
因此您需要将位移动到位,如下所示:
byte[] packetArrayBytes = new byte[2];
uint intA = 0xF; // Allowed range is 0-15 (0x0-0xF)
uint intB = 0xABC; // Allowed range is 0-4095 (0x0-0xFFF)
// Need to convert from uint to bytes:
byte[] bytesA = BitConverter.GetBytes(intA);
byte[] bytesB = BitConverter.GetBytes(intB);
byte a = bytesA[0]; // a is 0x0F
byte b = bytesB[1]; // b is 0x0A
int c = 0x00; // c is 0x00
int d = bytesB[0]; // d is 0xBC
// Mask out 4 least significant bits of a,
// then shift 4 bits left to place them in the most significant bits (of the byte),
// then OR them into c.
c |= (a & 0x0F) << 4; // c is now 0xF0
// Mask out 4 least significant bits of b,
// then OR them into c.
c |= b & 0x0F; // c is now 0xFA
packetArrayBytes[0] = (Byte)c;
packetArrayBytes[1] = (Byte)d;
Console.WriteLine(BitConverter.ToString(packetArrayBytes)); // Prints "FA-BC"
完成这些操作后,a
和 b
的值应该像这样放在字节 c
和 d
中:
c: 0xFA
d: 0xBC
。然后您可以将其放入数组中。
要取回这些值,只需反向执行这些相同的操作即可。
如果 a
和 b
是有符号值,我相信相同的操作有效,但您必须确保在将数据读回时没有将它们解释为无符号数字。