javabit-manipulationbit-shiftbit-packing

Shift byte value into int


I am attempting to store a single byte value into a position within an int, however, I am having trouble figuring out how this would be done. I have shifted the byte that i want to store in the int to the correct value, but I am at a loss as to how i then combine this with the value.

public static int ibyteToInt(int b, int pos, int val)
    {
        return ((b & 0xff) << (8 * pos)) ??;
    }

The simplest solution would be to unpack the 3 other bytes from the int and then recombine the 4 bytes into an int but of course this would not be very performant.

public static int bytesToInt(byte a, byte b, byte c, byte d)
    {
        return ((a & 0xff) << 0) | ((b & 0xff) << 8) | ((c & 0xff) << 16) | ((d & 0xff) << 24);
    }

Solution

  • An other simple solution is clearing out the target byte, then OR-ing in the new value:

    int replaceByte(int value, byte b, int pos)
    {
        return (value & ~(0xFF << (pos * 8))) | ((b & 0xFF) << (pos * 8));
    }
    

    This is very similar to how to do the same thing in C#, but Java requires & 0xFF to prevent sign-extension of the byte. If the "byte" is a value between 0 and 255 and passed in as an int, that step is not required.