Total Pageviews

Sunday, November 13, 2011

Java: use signed types to store unsigned values

short, int, long are always signed in Java. However, it only matters if you are doing math with it. Otherwise, you can store unsigned values using the signed types by utilizing the sign bit.

If you do need to do some math:

1) for unsigned short, us,

convert it to int by masking: int i = us & 0xffff;

Do all arithmetic with int operands, modulo 0xffff.

When you are done, cast the result back to int and transmit it.

2) for unsigned int, ui,

convert it to long by masking: long l = ui & 0xffffffffL;

Do all arithmetic with long operands, modulo 0xffffffffL.

When you are done, cast the result back to int and transmit it.

No comments:

Post a Comment