JAVA – Signed vs unsigned integer (vs C/C++)

source  – extract(s) :

>> C/C++:

>>> Java:

When an integer is signed, one of its bits becomes the sign bit, meaning that the maximum magnitude of the number is halved. (So an unsigned 32-bit int can store up to 232-1, whereas its signed counterpart has a maximum positive value of 231-1.)

Signed vs unsigned shifts

An important exception is the right shift operator, represented by two « greater than » symbols: >>. In both C/C++ and Java, this operator performs sign extension: that is, as well as shifting the bits of the number one place to the right, it preserves the sign. Specifically, after performing the shift, it copies the sign bit (the leftmost bit) into the leftmost position.

Now, if we’re treating an integer as unsigned, then we don’t want to copy the sign bit, because it doesn’t actually represent the sign! Instead, we want to leave it as zero. To achieve this, in Java, instead of writing >>, we write >>>. This variant of the shift is sometimes called a logical shift, and the previous variant— which takes account of the sign— an arithmetic shift. At the machine code level, most architectures in fact provide different instructions for the two shifts, and the C/C++ compiler chooses the appropriate one depending on whether we’ve declared the variable in question as unsigned. In Java, we must explicitly say which type we require.

  1. Pas encore de commentaire.

Vous devez être connecté pour poster un commentaire.