[英]C# - Shifting and reversing the order of bits in a byte array
I am trying to get the correct int out of an array of bytes. 我试图从字节数组中获取正确的int。 The bytes is read from a RFIDTag via POS for .Net.
通过POS for .Net从RFIDTag读取字节。 (Acctually I need 18 bits)
(大约需要18位)
In binary the byte array is as follows: 00001110 11011100 00000000 00011011 10000000 二进制格式的字节数组如下:00001110 11011100 00000000 00011011 10000000
What I need to get out of it is: 00 00000000 11101101 (int = 237) 我需要摆脱的是:00 00000000 11101101(int = 237)
From the original bytes that would be the following bits in reverse order: ------10 11011100 00000000 从原始字节开始将以相反的顺序为以下位:------ 10 11011100 00000000
I have been looking at bitArray. 我一直在看bitArray。 Array.Reverse.
Array.Reverse。 And several ways of shifting bits.
以及几种移位位的方法。 But I just can't wrap my head around this one.
但是我只是无法绕过这个头。
Can anyone point me in the correct direction? 谁能指出我正确的方向?
You can get the bits and reverse them like this: 您可以像这样获取位并反转它们:
byte[] data = { 0x0E, 0xDC, 0x00, 0x1B, 0x80 };
// get only first four bytes
byte[] bits = new byte[4];
Array.Copy(data, 0, bits, 0, 4);
// reverse array if system uses little endian
if (BitConverter.IsLittleEndian) {
Array.Reverse(bits);
}
// get a 32 bit integer from the four bytes
int n = BitConverter.ToInt32(bits, 0); // 0x0EDC001B
// isolate the 18 bits by shifting and anding
n >>= 8; // 0x000EDC00
n &= 0x0003FFFF; // 0x0002DC00
// reverse by shifting bits out to the right and in from the left
int result = 0;
for (int i = 0; i < 18; i++) {
result = (result << 1) + (n & 1);
n >>= 1;
}
Console.WriteLine(result);
Output: 输出:
237
Maybe 也许
// 00001110 11011100 00000000 00011011 10000000
// 0E DC 00 1B 80
byte[] info = new byte[] { 0x0E, 0xDC, 0x00, 0x1B, 0x80 };
int result = (info[0] << 4) | (info[1] >> 4);
Console.WriteLine(result); // ==> 237
info[0] << 4
turns 0E
into E0
. info[0] << 4
将0E
转换为E0
。
>> 4
turns DC
into 0D
. >> 4
将DC
变成0D
。
|
ORs E0
and 0D
into ED
which is decimal 237
将
E0
和0D
为ED
(十进制为237
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.