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

十年热恋 提交于 2019-12-02 08:09:06

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.

>> 4 turns DC into 0D.

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

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