To convert a binary byte to octal just divide the byte
into three nibbles. The first nibble has two bits and
the next two nibbles each have three. For example,
convert the binary value 01010011 to octal.
Binary 01 010 011
Octal 1 2 3
To convert a binary value to hexadecimal just divide the
byte into two nibbles of four bits each.
Binary 0111 1111
Hex 7 f
The following table demonstrates a set of conversions.
Base Conversion Table
| Decimal |
Binary |
Octal |
Binary |
Hexadecimal |
| 0 | 00 000 000 | 0 | 0000 0000 | 0 |
| 1 | 00 000 001 | 1 | 0000 0001 | 1 |
| 2 | 00 000 010 | 2 | 0000 0010 | 2 |
| 3 | 00 000 011 | 3 | 0000 0011 | 3 |
| 4 | 00 000 100 | 4 | 0000 0100 | 4 |
| 5 | 00 000 101 | 5 | 0000 0101 | 5 |
| 6 | 00 000 110 | 6 | 0000 0110 | 6 |
| 7 | 00 000 111 | 7 | 0000 0111 | 7 |
| 8 | 00 001 000 | 10 | 0000 1000 | 8 |
| 9 | 00 001 001 | 11 | 0000 1001 | 9 |
| 10 | 00 001 010 | 12 | 0000 1010 | a |
| 11 | 00 001 011 | 13 | 0000 1011 | b |
| 12 | 00 001 100 | 14 | 0000 1100 | c |
| 13 | 00 001 101 | 15 | 0000 1101 | d |
| 14 | 00 001 110 | 16 | 0000 1110 | e |
| 15 | 00 001 111 | 17 | 0000 1111 | f |
| 16 | 00 010 000 | 20 | 0001 0000 | 10 |
| 26 | 00 011 010 | 32 | 0001 1010 | 1a |
| 36 | 00 100 100 | 44 | 0010 0100 | 24 |
| 46 | 00 101 110 | 56 | 0010 1110 | 2e |
| 56 | 00 111 000 | 70 | 0011 1000 | 38 |
| 66 | 01 000 010 | 102 | 0100 0010 | 42 |
| 76 | 01 001 100 | 114 | 0100 1100 | 4c |
| 86 | 01 010 110 | 126 | 0101 0110 | 56 |
| 96 | 01 100 000 | 140 | 0110 0000 | 60 |
| 106 | 01 101 010 | 152 | 0110 1010 | 6a |
| 116 | 01 110 100 | 164 | 0111 0100 | 74 |
| 126 | 01 111 110 | 176 | 0111 1110 | 7e |
Here's an example question that prints Byte.MAX_VALUE in binary,
octal, decimal, and hex.
Question 9
class A {
public static void main(String args[]) {
System.out.print(Integer.toBinaryString(Byte.MAX_VALUE)+",");
System.out.print(Integer.toOctalString(Byte.MAX_VALUE)+",");
System.out.print(Integer.toString(Byte.MAX_VALUE)+",");
System.out.print(Integer.toHexString(Byte.MAX_VALUE));
}
}
What is the result of attempting to compile and run the program?
a. Prints: 1111111,177,127,7f
b. Prints: 11111111,377,256,ff
c. Compiler Error
d. Runtime Error
e. None of the Above
The binary representation of Byte.MAX_VALUE is as follows.
01111111
The Integer.toBinaryString method does not print the leading
zero. Instead, it only prints the seven bits that are set
to one as follows.
1111111
To convert the binary byte to octal just divide the byte
into three nibbles.
Binary 01 111 111
Octal 1 7 7
To convert Byte.MAX_VALUE to hexadecimal just divide the
byte into two four bit nibbles.
Binary 0111 1111
Hex 7 f
To convert Byte.MAX_VALUE to decimal raise 2 to the
seventh power and then subtract one. The result is 127.