First memorize this Powers of Two table, at least up to 27 = 128.
In CSC 212, we will only be working with one byte integers (byte variable type) with powers of two up to 128.
Example 1: Convert 00010110 (binary) to decimal.
Solution: Each binary digit (called a bit) represents a power of two:
Power of Two | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
Digit | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 0 |
Therefore, the value in decimal is
Example 2: Convert 22 (decimal) to binary.
Solution: Repeatedly subtract the largest power of two that can be subtracted from 22.
Power of 2 22 - 16 4 -- 6 - 4 2 -- 2 - 2 1 -- 0
Therefore 22 can be written as 22 = 16 + 4 + 2. Then
First memorize this Hex Digits table:
Then for each hex digit, replace it by the 4 bits in the binary column.
Example 3: Convert 6D (hex) to binary:
Solution: 6 --> 0110 and D --> 1101, so 6D --> 01101101.
Group the binary bits into groups of 4. Then translate each group of 4 bits (called a nybble!) into hex. Each nybble is equivalent to one hex digit.
Example 4: Convert 6D (hex) to binary:
Solution: 01101101 --> 0110 1101 --> 6 D --> 6D.
The hex value 6D is written as 0x6D in Java source code.