javabinary

Split Unsigned 32-bit Integer into Two 16-bit numbers that can be rebuilt


Is it possible to split an unsigned 32 bit Integer in Java, into two separate 16 bit numbers that can later be added together to get the original number.


Solution

  • You can use bitwise operations, including shifts.

    First disassemble:

    int original32 = 1000;
    int high16 = original32 >>> 16;
    int low16 = original32 & 0xFFFF;
    System.out.println(high16);
    System.out.println(low16);
    

    Here, to get lower 16 bits, we just mask the value to zero-out higher 16 bits. To get higher 16 bits, we shift them to the right.

    Rebuild:

    int rebuilt32 = (high16 << 16) | (low16 & 0xFFFF);
    System.out.println(rebuilt32);
    

    Here we shift higher 16 bits back left and then 'add' (actually, OR) lower bits.