Bit manipulation in a nutshell
In Java, we can manipulate bits of the following data types: byte
(8-bit), short
(16-bit), int
(32-bit), long
(64-bit), and char
(16-bit).
For example, let's use the positive number, 51. In this situation, we have the following statements:
- The binary representation of 51 is 110011.
- Because 51 is an
int
, it is represented as a 32-bit value; that is, 32 values of 1 or 0 (from 0 to 31). - All the positions to the left of 110011 are actually filled with zeros, up to 32 bits in total.
- This means that 51 is 00000000 00000000 00000000 00110011 (we render it as 110011 since the additional zeros are usually not needed for displaying the binary representation).
Obtaining the binary representation of a Java integer
How do we know that 110011 is the binary representation of 51? How can we compute the binary representation of 112 or any other Java integer? A simple approach consists of successively dividing the number by 2 until...