简体   繁体   English

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

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

I am trying to transfer a certain number of bits in a byte to the beginning of an int but its not working out as planned. 我正在尝试将某个字节中的一定数量的位传输到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 ;
}

eg, with offset 2 and len 3 of byte 00111000 should produce the int> 00000000000000000000000000000110 例如,偏移量2和字节00111000的len 3应该产生int> 00000000000000000000000000000110

I only need to put the bits at the beginning of the int but I would need to move any bits that have previously been assigned to the left so they are not overridden, hence the bitsInUse variable. 我只需要将这些位放在int的开头,但我需要将先前已分配给左侧的所有位移动,以使它们不会被覆盖,因此,bitsInUse变量。

This should do what you want (I have changed some of variable names). 这应该做您想要的(我已经更改了一些变量名)。 Note that you must pass in values such that currBitsUsed >= len , or the shifted curr and b bits will collide. 请注意,您必须传入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);
}

And here is a version that automatically calculates the number of bits to shift curr to avoid a collision. 这里是自动计算的位数移位版本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