C# - 移和字节数组反转位的顺序 [英] C# - Shifting and reversing the order of bits in a byte array

查看:741
本文介绍了C# - 移和字节数组反转位的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图得到正确的int的列的字节数组。
字节是从通过POS一个RFIDTag对于.NET读取。
(Acctually我需要18位)

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)

在二进制字节数组如下:
00001110 11011100 00000000 00011011千万

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

我需要摆脱它是:
00 00000000 11101101
(INT = 237)

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

从原来的字节,这将是在相反的顺序以下位:
------ 10 11011100 00000000

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

我一直在寻找bitArray。 Array.Reverse。而几种方式转变位。但我不能换我的头周围这一个。

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?

推荐答案

您可以得到位,并扭转他们是这样的:

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);

输出:

237

这篇关于C# - 移和字节数组反转位的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆