Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer to BinaryString removes leading zero in Java

Tags:

java

binary

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));
like image 207
JackSlayer94 Avatar asked Feb 05 '23 13:02

JackSlayer94


1 Answers

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')
like image 107
ΦXocę 웃 Пepeúpa ツ Avatar answered Feb 07 '23 18:02

ΦXocę 웃 Пepeúpa ツ