我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。
Java中有没有内置函数?
我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。
Java中有没有内置函数?
当前回答
试试这个方法:
public class Bin {
public static void main(String[] args) {
System.out.println(toBinary(0x94, 8));
}
public static String toBinary(int a, int bits) {
if (--bits > 0)
return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
else
return (a&0x1)==0?"0":"1";
}
}
10010100
其他回答
假设你指的是“内置”:
int x = 100;
System.out.println(Integer.toBinaryString(x));
请参阅整型文档。
(Long有一个类似的方法,BigInteger有一个实例方法,你可以在其中指定基数。)
古老的学校:
int value = 28;
for(int i = 1, j = 0; i < 256; i = i << 1, j++)
System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
输出(最低有效位在0位置):
0 0 1 0 2 1 3 1 4 1 5 0 6 0 7 0
“ 长k = 272214023L;
字符串长= String.format(64年代“%”,Long.toBinaryString (k)。替换(',' 0 ');
String long1 = String.format("%64s",Long.toBinaryString(k))。replace(' ','0').replaceAll("(\d{8})","$1 "); ` 打印: 0000000000000000000000000000000000000000000
00000000 00000000 00000000 00000000 00000000 0000000
简单又简单的解决方法。
public static String intToBinaryString(int integer, int numberOfBits) {
if (numberOfBits > 0) { // To prevent FormatFlagsConversionMismatchException.
String nBits = String.format("%" + numberOfBits + "s", // Int to bits conversion
Integer.toBinaryString(integer))
.replaceAll(" ","0");
return nBits; // returning the Bits for the given int.
}
return null; // if the numberOfBits is not greater than 0, returning null.
}
System.out.println(Integer.toBinaryString(343));