任何类型的数在计算机底层存储都是以二进制的形式,那么如何知道一个数的二进制数是多少呢?l
public class PrintBinary {
public static void printBinary(Object num) {
if (num == null) {
return;
}
if (num instanceof Integer) {
for (int i = 31; i >= 0; i--) {
System.out.print(((int) num & (1 << i)) == 0 ? "0" : "1");
}
System.out.println();
} else if (num instanceof Long) {
for (int i = 63; i >= 0; i--) {
System.out.print(((Long) num & (1L << i)) == 0 ? "0" : "1");
}
System.out.println();
}
}
public static void main(String[] args) {
printBinary(1);
printBinary(Long.MAX_VALUE);
}
}
利用位运算可以快速得出int型、long型整数的二进制数。
标签:java,二进制,打印,System,int,num,print,out From: https://blog.csdn.net/weixin_56812051/article/details/144341941