In Java, Integer.divideUnsigned(dividend, divisor) divides two int values while treating their 32 bits as unsigned numbers. The quotient is returned in an int.
The normal / operator is signed, so it gives a different answer whenever a value has its top bit set (a negative int). For example, -1 divided by 2 is 0 with /, but as an unsigned value 4294967295 divided by 2 is 2147483647.
A static method of java.lang.Integer (since Java 8): call it on the class, as Integer.divideUnsigned(...). Integer lives in java.lang, so no import is needed. divideUnsigned() was added in Java 8.
Syntax
Pass the dividend first, then the divisor.
Java
int a = Integer.divideUnsigned(100, 7); // 14
int b = Integer.divideUnsigned(-1, 2); // 2147483647 (4294967295 / 2)
int c = -1 / 2; // 0 (signed division)
Both arguments are read as unsigned. The result is stored in an int, so a large quotient may print as a negative number; use toUnsignedString() to show it.
Library declarations
Java
// java.lang.Integer
public static int divideUnsigned(int dividend, int divisor)
Parameters
Parameter
Description
dividend (int)
The number to divide, read as unsigned.
divisor (int)
The number to divide by, read as unsigned. It must not be 0.
Return Value
Return Value
Description
int
The unsigned quotient, rounded down. Print it with toUnsignedString() if it may be above Integer.MAX_VALUE.
5 / -1 (unsigned): 0
-1 / -1 (unsigned): 1
-2 / -1 (unsigned): 0
divide by zero -> ArithmeticException
How It Works
A negative divisor is huge. As unsigned, -1 is 4294967295, and 5 divided by that is less than 1, so the result is 0.
Same number twice. -1 divided by -1 is 1, as for any number divided by itself.
Just below the divisor. -2 is 4294967294, which is smaller than the divisor, so the quotient is 0.
Zero still fails. A divisor of 0 throws ArithmeticException, even though unsigned numbers cannot be negative.
Frequently Asked Questions
It divides two ints as unsigned 32-bit numbers and returns the quotient as an int.
The / operator is signed. When a number is negative as an int, / uses the negative value, while divideUnsigned uses the large unsigned value with the same bits.
Yes. A divisor of 0 throws ArithmeticException.
The quotient is stored in a signed int. If it is above 2147483647, the top bit is set. Print it with Integer.toUnsignedString.
Call Integer.remainderUnsigned(a, b) with the same arguments.