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?
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.
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.
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.
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.)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With