0

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.

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

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.

daedalus
  • 105
  • 2
  • 10

1 Answers1

1

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.

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.

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);
} 
cybersam
  • 63,203
  • 6
  • 53
  • 76
  • Thanks! works great!, I realized that I can do away with curBitsUsed and just use (curr << len) as it will always be the same value because i'm just making room for new bits and I don't need to know whats already in use because it will just be shifted left anyhow. – daedalus Aug 21 '15 at 14:09
  • I changed it to> public static int transfer(byte b, int offset, int len, int curr) { return (curr << len) | ((byte)((b) >>> offset) & (byte)((1 << len) - 1)); } – daedalus Aug 21 '15 at 14:22
  • If `len` is guaranteed to never be less than the length of the significant data in `curr`, that will work. But it will not work in general. In any case, please consider Accepting my answer. – cybersam Aug 21 '15 at 16:47