dli*_*eaa 0 c# binary byte bits bitarray
我试图从字节数组中获取正确的int。通过POS for .Net从RFIDTag读取字节。(大约需要18位)
二进制格式的字节数组如下:00001110 11011100 00000000 00011011 10000000
我需要摆脱的是:00 00000000 11101101(int = 237)
从原始字节开始将以相反的顺序为以下位:------ 10 11011100 00000000
我一直在看bitArray。Array.Reverse。以及几种移位位的方法。但是我只是无法绕过这个头。
谁能指出我正确的方向?
您可以像这样获取位并反转它们:
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);
Run Code Online (Sandbox Code Playgroud)
输出:
237
Run Code Online (Sandbox Code Playgroud)