繁体   English   中英

Java以字节和整数的偏移量和长度传输位

[英]java transfer bits at offset and length from byte to int

我正在尝试将某个字节中的一定数量的位传输到int的开头,但无法按计划进行。

public int transfer(byte b, int offset, int len, int dest, int bitsInUSe){
             byte mask  = (byte) ((byte)  ((1 << len) - 1) << offset);
               dest = dest<< bitsInUSe;
          dest = b & mask;
              return dest ;
}

例如,偏移量2和字节00111000的len 3应该产生int> 00000000000000000000000000000110

我只需要将这些位放在int的开头,但我需要将先前已分配给左侧的所有位移动,以使它们不会被覆盖,因此,bitsInUse变量。

这应该做您想要的(我已经更改了一些变量名)。 请注意,您必须传入currBitsUsed >= len这样的值,否则移位的currb位将发生冲突。

public int transfer(byte b, int offset, int len, int curr, int currBitsUsed) {
    byte mask = (byte)((1 << len) - 1);
    return (curr << currBitsUsed) | ((byte)((b) >>> offset) & mask);
}

这里是自动计算的位数移位版本curr以避免碰撞。

public int transfer(byte b, int offset, int len, int curr) {
    int currShift = Math.max(32 - Integer.numberOfLeadingZeros(curr), len);
    byte mask = (byte)((1 << len) - 1);
    return (curr << currShift) | ((byte)((b) >>> offset) & mask);
} 

暂无
暂无

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

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