对BinaryString的整数删除Java中的前导零 [英] Integer to BinaryString removes leading zero in Java
问题描述
我想将整数转换为二进制字符串.我选择使用Java允许 Integer.toBinaryString(n)
的本机函数.但不幸的是,这会修剪我的输出中的前导零.例如,假设输入为 18
,输出为 10010
,但实际输出应该为 010010
.是否有比编写用户定义的函数更好的/将int转换为字符串的捷径?还是我在这里做错了什么?
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));
推荐答案
它应该是 010010 ....
its suppose to be 010010....
不是真的,整数类型由32位组成,因此应该为:
not really, integer type have made up from 32 bits, so it should be:
000000000000000000000000010010 ,java不会打印该信息,在这种情况下,左零与该数字的大小无关.
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')
或者在您的情况下使用6位
or in your case using 6 bits
String.format("%6s", Integer.toBinaryString(18)).replace(' ', '0')
这篇关于对BinaryString的整数删除Java中的前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!