简体   繁体   English

从第一个字节中删除位,然后重新加入这些位

[英]Removing bits from first byte and then rejoining the bits

I have a devious little problem to which I think I've come up with a solution far more difficult than needs to be. 我有一个曲折的小问题,我想我想出一个比所需困难得多的解决方案。

The problem is that I have two bytes. 问题是我有两个字节。 The first two bits of the first byte are to be removed (as the value is little endian, these bits are effectively in the middle of the 16 bit value). 第一个字节的前两位将被删除(由于该值是小端序,因此这些位实际上位于16位值的中间)。 Then the least significant two bits of the second byte are to be moved to the most significant bit locations of the first byte, in place of the removed bits. 然后,将第二个字节的最低有效两位移动到第一个字节的最高有效位位置,以代替删除的位。

My solution is as follows: 我的解决方案如下:

byte firstByte = (byte)stream.ReadByte(); // 01000100
byte secondByte = (byte)stream.ReadByte(); // 00010010
// the first and second byte equal the decimal 4676 in this little endian example

byte remainderOfFirstByte = (byte)(firstByte & 63); // 01000100 & 00111111 = 00000100

byte transferredBits = (byte)(secondByte  << 6); // 00010010 << 6 = 10000000

byte remainderOfSecondByte = (byte)(secondByte >> 2); // 00010010 >> 2 = 00000100

byte newFirstByte = (byte)(transferredBits | remainderOfFirstByte); // 10000000 | 00000100 = 10000100
int result = BitConverter.ToInt32(new byte[]{newFirstByte, remainderOfSecondByte, 0, 0}, 0); //10000100 00010000 (the result is decimal 1156)

Is there an easier way* to achieve this? 有没有更简单的方法*来实现这一目标? *less verbose, perhaps an inbuilt function or trick I'm missing? *不太冗长,也许是我缺少的内置函数或技巧? (with the exception of doing both the & and << on the same line) (除了在同一行上同时执行&和<<之外)

You don't have to mask out bits that a shift would throw away anyway. 您不必掩盖任何移位都会丢掉的部分。 And you don't have to transfer those bits manually. 而且您不必手动传输这些位。 So it becomes this: (not tested) 就是这样:(未经测试)

int result = (secondByte << 6) | (firstByte & 0x3F);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM