"Unsigned" means that the integer has no negative sign, it's either zero or a positive number. With four bits we can represent 16 different numbers, from 0 to 15.
When using bits, the amount of numbers we can represent is always a power of two since a bit has two states, zero or one. The formula to calculate how many numbers you can represent with a given amount of bits is .
21 = 2 ← One bit lets us express two different numbers.
22 = 4
23 = 8
24 = 16
25 = 32
26 = 64
27 = 128
28 = 256 ← Eight bits are a byte. If that byte is an unsigned integer, it can represent the numbers from 0 to 255.
216 = 65,536
232 = 4,294,967,296 ← Java uses 32 bits for integers, the data type is called int. But they are signed to allow for negative numbers. To represent numbers below zero, Java uses two's complement (see below).
264 = 18,446,744,073,709,551,616 ← Java uses 64 bits for the data type long. 64 bits allow for 18 quintillion (18 x 1018) numbers.
Signed Integers with Sign Bit
bits
decimal
0
0
0
0
=
0
-
4
2
1
Signed Integers with Ones' Complement
bits
decimal
0
0
0
0
=
0
-7
4
2
1
1
1
1
1
← All ones
-
0
0
0
0
← Number to negate (0)
—
—
—
—
1
1
1
1
← Ones' complement (-0)
To negate a number using ones' complement, we flip all the bits. Flipping bits is equivalent to subtracting them from a binary number consisting of all ones: 1111
Signed Integers with Two's Complement
bits
decimal
0
0
0
0
=
0
-8
4
2
1
1
0
0
0
0
← Power of two: (16)
-
0
0
0
0
← Number to negate (0)
—
—
—
—
—
1
0
0
0
0
← Two's complement (0)
To negate a number using two's complement, we flip all the bits and add one. This is equivalent to subtracting it from a power of two: , which is: 1 0000