Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print an integer in binary format in Java

Tags:

java

I have a number and I want to print it in binary. I don't want to do it by writing an algorithm.

Is there any built-in function for that in Java?

like image 406
akshayxyz Avatar asked Mar 10 '11 17:03

akshayxyz


People also ask

How do you print an integer in binary?

To print binary representation of unsigned integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print “1” else print “0”. Now check whether 30th bit is ON or OFF, if it is ON print “1” else print “0”, do this for all bits from 31 to 0, finally we will get binary representation of number.

How do you convert int to binary in Java?

toBinaryString(int i) To convert an integer to binary, we can simply call the public static String toBinaryString(int i) method of the Integer class. This method returns the binary string that corresponds to the integer passed as an argument to this function.

How do you write a number represented in binary?

As an example, the number CA3 16 = 1100 1010 00112 (11002 = C16 , 10102 = A16, 00112 = 3 16). It is convenient to write the binary number with spaces after every fourth bit to make it easier to read.


2 Answers

Assuming you mean "built-in":

int x = 100; System.out.println(Integer.toBinaryString(x)); 

See Integer documentation.

(Long has a similar method, BigInteger has an instance method where you can specify the radix.)

like image 73
Jon Skeet Avatar answered Sep 24 '22 17:09

Jon Skeet


Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int, representation)

Integer.toString(100,8) // prints 144 --octal representation  Integer.toString(100,2) // prints 1100100 --binary representation  Integer.toString(100,16) //prints 64 --Hex representation 
like image 23
Mohasin Ali Avatar answered Sep 25 '22 17:09

Mohasin Ali