views:

118

answers:

1

I have code that stores values in the range 0..255 in a Java byte to save space in large data collections (10^9 records spread over a couple hundred arrays).

Without additional measures on recovery, the larger values are interpreted as being negative (because the Java integer types use two's complement representation).

I got this helpful hint from starblue in response to a related question, and I'm wondering if this technique is safe to rely on:

int iOriginal = 128, iRestore;
byte bStore = (byte) iOriginal; // reading this value directly would yield -128
iRestore = 0xff & bStore;
+3  A: 

Yes, it's safe, indeed it's the most effective way of converting a byte into an (effectively) unsigned integer.

The byte half of the and operation will be sign-extended to an int, i.e. whatever was in bit 7 will be expanded into bits 8-31.

Masking off the bottom eight bits (i.e. & 0xff) then gives you an int that has zero in every bit from 8 - 31, and must therefore be in the range 0 ... 255.

See a related answer I gave here.

Alnitak