What is the Integer.toBinaryString() method in Java?
The toBinaryString() static method of the Integer class in Java can be used to get the binary representation (base 2) of an integer value.
Syntax
The syntax of toBinaryString() is shown below.
public static String toBinaryString(int i);
Parameters
The toBinaryString() method takes an integer value as an argument.
Return value
The toBinaryString() method returns the binary (base 2) representation of the passed integer value as a String value.
If the argument is negative, then the result is the binary representation of the argument + .
Example
Let’s use the toBinaryString() method to convert an int to a binary string.
class IntToBinaryString {public static void main( String args[] ) {int i = 8;System.out.println("The binary value of " + i + " is : " + Integer.toBinaryString(i));int j = -1;System.out.println("The binary value of " + j + " is : " + Integer.toBinaryString(j));}}
Explanation
In the code above:
-
We create an
intvariableiand assign as the value. Then, we use thetoBinaryString()method to convert theintto a binary string. The binary value of is1000. -
We then call the
toBinaryStringmethod with a negative value as an argument, as shown below.
int j = -1;
Integer.toBinaryString(j);
If the argument is negative, the argument is converted to + argument ( = 4294967296) before binary conversion. In our case, we get the following:
=> 4294967296 + (- 1)
=> 4294967296 - 1
=> toBinaryString(4294967295)
=> 11111111111111111111111111111111
We get 11111111111111111111111111111111 as the result.