10 - > 0000 0000 0000 1010
15 - > 0000 0000 0000 1111
我尝试使用Integer.toBinaryString()
但打印
10 - > 1010
15 - > 1111
是否有可打印的短,所有16位还是我写我自己的一个功能。
10 - > 0000 0000 0000 1010
15 - > 0000 0000 0000 1111
我尝试使用Integer.toBinaryString()
但打印
10 - > 1010
15 - > 1111
是否有可打印的短,所有16位还是我写我自己的一个功能。
你可以垫左侧以0:
int x=10;//or whatever
String.format("%016d", Integer.parseInt(Integer.toBinaryString(x)));
追加手动0的可能有助于
String.format("%16s", Integer.toBinaryString(1)).replace(' ', '0')
会产生0000000000000001
您也可以使用下面的技巧来显示领导zero/s
。详情请看this thread。
int displayMask = 1 << (size - 1);
StringBuffer buf = new StringBuffer(size);
for (int c = 1; c <= size; c++)
{
buf.append((value & displayMask) == 0 ? '0' : '1');
value <<= 1;
}
根据this answerInteger.toBinaryString()
仅整数/ INT领先zeros
。它不适用于byte
。
您可以使用String.format()
在结果之前添加填充。填充必须是空格,因为Integer.toBinaryString()
返回String
。然后,你需要做的就是用零替换空格(0
)并分割每个半字节(第四位)。
import java.util.*;
public class BinaryNumberPrinter {
public static void main(String[] args) {
int[] numbers = { 10, 15 };
for (int number : numbers) {
String binaryValue = join(splitEveryFour(toShortBinary(number)), " ");
System.out.printf("%d -> %s%n", number, binaryValue);
}
}
public static String toShortBinary(int value) {
return String.format("%16s", Integer.toBinaryString(value)).replace(' ', '0');
}
public static List<String> splitEveryFour(String value) {
return Arrays.asList(value.split("(?<=\\G....)"));
}
public static String join(Iterable<? extends CharSequence> s, String delimiter) {
Iterator<? extends CharSequence> iter = s.iterator();
if (!iter.hasNext()) return "";
StringBuilder buff = new StringBuilder(iter.next());
while (iter.hasNext()) buff.append(delimiter).append(iter.next());
return buff.toString();
}
}
预期输出:
10 -> 0000 0000 0000 1010
15 -> 0000 0000 0000 1111