Home / Language / English / What is the Java equivalent of unsigned?

What is the Java equivalent of unsigned?

In C and C++, the unsigned modifier can be added to a integer variable declaration. It tells the compiler to treat the value of the variable as an unsigned value in arithmetic operations. Unsigned arithmetic is typically used:

Reference

  • when manipulating raw bytes: it’s often convenient to treat a byte as unsigned;
  • when performing bitwise operations: that is, cases such as hashing or randum number generation, where the numerical value of the number doesn’t actually have much sense, and we’re just interested in performing bitwise operations such as XOR, shifts etc and interpreting the number as a “series of bits”;
  • where the sign makes no sense, and/or where we’d rather have a larger possible range of positive values than the possibility of negative numbers: such as a memory location or file size.

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.)

In Java, all integer types are signed (except char). Although a questionable design, even bytes are signed in Java! So what do we do if we want to treat a value as unsigned in Java? In most typical cases in which unsigned values are used, it actually turns out not to be too difficult to get the same result in Java.

It’s important to remember that the unsigned keyword affects the interpretation, not the representation of a number. In other words, in cases where we aren’t interpreting a value arithmetically— so-called bitwise operations such as AND, OR, XOR— it makes essentially no difference whether a value is marked as “signed” or “unsigned”.

About Mohammad Khazab

Interested in this?

14-Year-Old Prodigy Programmer Dreams In Code

Fourteen-year-old programmer and software developer Santiago Gonzalez might just be the next Steve Jobs. He ...