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?
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
来源:https://stackoverflow.com/questions/14718797/c-sharp-shifting-and-reversing-the-order-of-bits-in-a-byte-array