C# - Shifting and reversing the order of bits in a byte array

南笙酒味 提交于 2019-12-20 05:57:45

问题


I am trying to get the correct int out of an array of bytes. The bytes is read from a RFIDTag via POS for .Net. (Acctually I need 18 bits)

In binary the byte array is as follows: 00001110 11011100 00000000 00011011 10000000

What I need to get out of it is: 00 00000000 11101101 (int = 237)

From the original bytes that would be the following bits in reverse order: ------10 11011100 00000000

I have been looking at bitArray. 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?


回答1:


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



回答2:


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.

>> 4 turns DC into 0D.

| ORs E0 and 0D into ED which is decimal 237



来源:https://stackoverflow.com/questions/14718797/c-sharp-shifting-and-reversing-the-order-of-bits-in-a-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!