我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。
Java中有没有内置函数?
我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。
Java中有没有内置函数?
当前回答
这是我格式化Integer输出的方式。toBinaryString方法:
public String toBinaryString(int number, int groupSize) {
String binary = Integer.toBinaryString(number);
StringBuilder result = new StringBuilder(binary);
for (int i = 1; i < binary.length(); i++) {
if (i % groupSize == 0) {
result.insert(binary.length() - i, " ");
}
}
return result.toString();
}
toBinaryString(0xABFABF, 8)的结果是“10101011 11111010 10111111” 对于toBinaryString(0xABFABF, 4)是“1010 1011 1111 1010 1011 1111”
其他回答
古老的学校:
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
它使用强大的位操作处理有符号和无符号值,并生成左边的第一个零。
public static String representDigits(int num) {
int checkBit = 1 << (Integer.SIZE * 8 - 2 ); // avoid the first digit
StringBuffer sb = new StringBuffer();
if (num < 0 ) { // checking the first digit
sb.append("1");
} else {
sb.append("0");
}
while(checkBit != 0) {
if ((num & checkBit) == checkBit){
sb.append("1");
} else {
sb.append("0");
}
checkBit >>= 1;
}
return sb.toString();
}
这个问题在java中很棘手(可能在其他语言中也是如此)。
Integer是32位有符号数据类型,但Integer. tobinarystring()返回整数参数的字符串表示形式,以2为基数的无符号整数。
因此,Integer.parseInt(Integer.toBinaryString(X),2)可以生成一个异常(有符号vs无符号)。
安全的方法是使用Integer.toString(X,2);这将生成一些不那么优雅的东西:
- 11110100110.
但它确实有效!!
for(int i = 1; i <= 256; i++)
{
System.out.print(i + " "); //show integer
System.out.println(Integer.toBinaryString(i) + " "); //show binary
System.out.print(Integer.toOctalString(i) + " "); //show octal
System.out.print(Integer.toHexString(i) + " "); //show hex
}
您可以使用位掩码(1<< k)和与数字做与操作! 1 << k在k位有1位!
private void printBits(int x) {
for(int i = 31; i >= 0; i--) {
if((x & (1 << i)) != 0){
System.out.print(1);
}else {
System.out.print(0);
}
}
System.out.println();
}