在Java中,将int转换为二进制字符串表示的最佳方式(理想情况下,最简单)是什么?
例如,假设int是156。它的二进制字符串表示应该是"10011100“。
发布于 2010-03-09 11:26:24
Integer.toBinaryString(int i)
发布于 2012-12-15 15:00:23
还有java.lang.Integer.toString(int i, int base)方法,如果您的代码有一天可以处理2(二进制)之外的基数,它会更合适。请记住,此方法只给出了整数i的无符号表示,如果它是负数,它将在前面添加一个负号。它不会使用二的补码。
发布于 2016-08-30 02:58:00
public static string intToBinary(int n)
{
String s = "";
while (n > 0)
{
s = ( (n % 2 ) == 0 ? "0" : "1") +s;
n = n / 2;
}
return s;
}
https://stackoverflow.com/questions/2406432
复制相似问题