Integer.toBinaryString()
Writes a number in binary. Related methods are toHexString() and toOctalString().
Available since: Java 1.0
Syntax
static String toBinaryString(int i)Parameters
| Parameter | Type | Description |
|---|---|---|
| i | int | An integer. |
Return value
StringA string of zeros and ones without leading zeros.
Examples
Binary and hex notation, and the reverse conversion:
void main() {
IO.println(Integer.toBinaryString(10));
IO.println(Integer.toHexString(255));
IO.println(Integer.toString(255, 8));
IO.println(Integer.parseInt("1010", 2));
}Output:
1010
ff
377
10Negative numbers are shown in two's complement — 32 bits:
void main() {
IO.println(Integer.toBinaryString(-1));
IO.println(Integer.bitCount(10));
}Output:
11111111111111111111111111111111
2Notes
Leading zeros are not printed. To get, say, 8 digits, use String.format("%8s", Integer.toBinaryString(5)).replace(' ', '0').
See also
- Integer.parseInt() — Converts a string containing an integer to an int.
- String.format() — Builds a string from a template with placeholders such as %s and %d.
Related recipes
In the tutorial
- Primitive types — Java's eight primitive types: int, long, double, float, char, boolean, byte and short, their ranges and overflow.