Integer to BinaryString removes leading zero in Java

南楼画角 提交于 2021-02-05 05:49:04

问题


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));

回答1:


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')



回答2:


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;
}


来源:https://stackoverflow.com/questions/43706904/integer-to-binarystring-removes-leading-zero-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!