How to convert a number to binary or hex
Short answer
Integer has ready-made methods for binary, octal and hexadecimal notation:
void main() {
int number = 255;
IO.println(Integer.toBinaryString(number));
IO.println(Integer.toOctalString(number));
IO.println(Integer.toHexString(number));
}Output:
11111111
377
ffAny radix
Integer.toString(n, radix) converts to any base from 2 to 36:
void main() {
IO.println(Integer.toString(255, 3));
IO.println(Integer.toString(35, 36));
}Output:
100110
zBack to a number
parseInt() with a second argument reads a string in the given base:
void main() {
IO.println(Integer.parseInt("1010", 2));
IO.println(Integer.parseInt("ff", 16));
}Output:
10
255With leading zeros
toBinaryString() does not add leading zeros. Pad the string yourself, and for hexadecimal use HexFormat:
void main() {
String bits = Integer.toBinaryString(5);
IO.println("0".repeat(8 - bits.length()) + bits);
IO.println(HexFormat.of().toHexDigits((byte) 10));
IO.println(HexFormat.of().formatHex(new byte[] {1, 127, -1}));
}Output:
00000101
0a
017fffCommon mistake
Being surprised by negative numbers. The methods show the internal representation — 32-bit two's complement:
void main() {
IO.println(Integer.toBinaryString(-1));
IO.println(Integer.toHexString(-1));
IO.println(Integer.toString(-1, 2));
}Output:
11111111111111111111111111111111
ffffffff
-1If you need a minus sign, use Integer.toString(n, 2).
Functions used in this recipe
- Integer.toBinaryString() — Writes a number in binary. Related methods are toHexString() and toOctalString().
- Integer.parseInt() — Converts a string containing an integer to an int.