The Laws of Cryptography:
Unsigned bytes in Java

by Neal R. Wagner

Copyright © 2001 by Neal R. Wagner. All rights reserved.

NOTE: This site is obsolete. See book draft (in PDF):

Law JB1: In the Java language, to right shift an integer amount shiftAmount, use the code

                int shiftedValue = (byteValue & 0xff) >> shiftAmount;

where byteValue is of type byte and shiftAmount is an int in the range from 0 to 8. A 0 for shiftAmount is the same as not doing the shift, but just to store an unsigned byte into an int type requires

                int shiftedValue = byteValue & 0xff;

Law JB2: In the Java language, logical and shifting operators work as follows:
  1. All operators return an int, so they must be cast to a byte if a byte is needed. This includes: &, |, ^, >>, >>>, and <<.
  2. Hex constants such as 0xff actually define an integer, so this is the same as 0x000000ff. For values bigger than Ox7f a cast to byte is needed.
  3. Arithmetic (except for / and %) with Java's signed bytes works just as if the bytes were unsigned, since there is no overflow.


Revision date: 2001-12-28. (Please use ISO 8601, the International Standard.)