Java Data Type How to - Use Integer as unsigned Integer


We would like to know how to use Integer as unsigned Integer.


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)

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

public class Main {
  public static void main(String[] args) {
    // Two negative integer values
    int x = -1;
    int y = -2;//from   ww  w . jav  a2 s  .  co  m

    // 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);

The code above generates the following result.