I wanted to convert an integer to binary string. I opted to use the native function that java allows Integer.toBinaryString(n)
. But unfortunately, this trims the leading zero from my output. Lets say for example, I give the input as 18
, it gives me output of 10010
but the actual output is supposed to be 010010
. Is there a better/short-way to convert int to string than writing a user defined function? Or am I doing something wrong here?
int n = scan.nextInt();
System.out.println(Integer.toBinaryString(n));
its suppose to be 010010....
not really, integer type have made up from 32 bits, so it should be:
000000000000000000000000010010, java is not going to print that information, left zeros are in this case not relevant for the magnitude of that number..
so you need to append the leading zeros by yourself, since that method is returning a string you can format that:
String.format("%32s", Integer.toBinaryString(18)).replace(' ', '0')
or in your case using 6 bits
String.format("%6s", Integer.toBinaryString(18)).replace(' ', '0')
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