4

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));
JackSlayer94
  • 725
  • 2
  • 12
  • 33
  • Possible duplicate of [how to combine 2 string using or operator?](http://stackoverflow.com/questions/43658281/how-to-combine-2-string-using-or-operator) (I know with that title it sounds crazy, but take a look at [my answer there](http://stackoverflow.com/a/43658944/5772882)). – Ole V.V. Apr 30 '17 at 14:16

2 Answers2

8

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')
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83
0

From the documentation:

This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s

So no, you aren't doing something wrong. To get your desired output, you'll need to write a small method yourself. One way would be to prepare a string with zeros with the length of your desired output, substring it and append the value. Like

private String getBinaryString6Bit(int n) {
    String binaryNoLeadingZero = Integer.toBinaryString(n);
    return "000000"
            .substring(binaryNoLeadingZero.length())
            + binaryNoLeadingZero;
}
petul
  • 943
  • 9
  • 16