Search code examples
javaintegerpackingshort

In java is it possible to pack a integer number that is expected not to be negative & be final (not overflow) into a short?


"Unsigned int" into a short and back. Is this possible? How to do it if so?

Grrrr. I forgot how signed numbers are implemented. The question makes no sense. Thanks anyway. I was going to downvote myself, you can do it instead.


Solution

  • I'm not sure I fully understand the question but if you are sure that your int fit into a short (you number is between 0 and 2^16) you can always cast your int to a short:

    int i = 65536;
    short s = (short) i;
    

    And to get the unsigned value back: int i2 = s & 0xFFFF; System.out.println(i2);

    The s & 0xFFFF will upcast s to an int and the bit mask will "convert" the negative number to it's unsigned value (sort of). Remember that FFFF in a short variable -1 not 65536.