Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
iintAn 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
10

Negative numbers are shown in two's complement — 32 bits:

void main() {
    IO.println(Integer.toBinaryString(-1));
    IO.println(Integer.bitCount(10));
}

Output:

11111111111111111111111111111111
2

Notes

Leading zeros are not printed. To get, say, 8 digits, use String.format("%8s", Integer.toBinaryString(5)).replace(' ', '0').

See also

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.

Thanks for reading!

Donate to the site — we work hard for you.