Java - Unsigned Numeric Operations

Why Unsigned Numeric Operations

Java does not support unsigned primitive integer data types.

A byte takes 8 bits; its range is -128 to 127. If you were to store only positive numbers in a byte, its range would have been 0 to 255.

Methods

Java has some static methods in wrapper classes that support operations treating the bits in the signed values as if they are unsigned integers.

The Byte class contains two static methods:

int toUnsignedInt(byte x)
long toUnsignedLong(byte x)

Demo

public class Main {
  public static void main(String[] args) {
    byte b = -1;// ww w.  j ava2 s  .  c o m
    int x = Byte.toUnsignedInt(b);
    System.out.println("Signed value in byte = " + b);
    System.out.println("Unsigned value in byte = " + x);

  }
}

Result

The Integer class contains the following static methods to support unsigned operations and conversions:

int compareUnsigned(int x, int y)
int divideUnsigned(int dividend, int divisor)
int parseUnsignedInt(String s)
int parseUnsignedInt(String s, int radix)
int remainderUnsigned(int dividend, int divisor)
long toUnsignedLong(int x)
String toUnsignedString(int i)
String toUnsignedString(int i, int radix)

Integer class does not contain addUnsigned(), subtractUnsigned(), and multiplyUnsigned() you can just use the normal operators.

The following code shows the division operation on two int variables as if their bits represent unsigned values:

Demo

public class Main {
  public static void main(String[] args) {
    int x = -1;/*  w  ww.  jav  a 2s.c o m*/
    int y = -2;

    // Performs signed division
    System.out.println("Signed x = " + x);
    System.out.println("Signed y = " + y);
    System.out.println("Signed x/y = " + (x/y));

    // Performs unsigned division by treating x and y holding unsigned values
    long ux = Integer.toUnsignedLong(x);
    long uy = Integer.toUnsignedLong(y);
    int uQuotient = Integer.divideUnsigned(x, y);
    System.out.println("Unsigned x = " + ux);
    System.out.println("Unsigned y = " + uy);
    System.out.println("Unsigned x/y = " + uQuotient);


  }
}

Result

Related Topic