我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。

Java中有没有内置函数?


当前回答

由于没有答案被接受,也许您的问题是关于如何在二进制文件中存储整数。 dataoutputstream可能就是您要找的:https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

其他回答

我需要一些东西可以很好地打印出来,并把每n位的比特分开。换句话说,显示前导零并显示如下内容:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

我是这么写的:

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

像这样调用它:

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}

它使用强大的位操作处理有符号和无符号值,并生成左边的第一个零。

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();
    }

古老的学校:

    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

解决方案使用32位显示掩码,

public static String toBinaryString(int n){

    StringBuilder res=new StringBuilder();
    //res= Integer.toBinaryString(n); or
    int displayMask=1<<31;
    for (int i=1;i<=32;i++){
        res.append((n & displayMask)==0?'0':'1');
        n=n<<1;
        if (i%8==0) res.append(' ');
    }

    return res.toString();
}


 System.out.println(BitUtil.toBinaryString(30));


O/P:
00000000 00000000 00000000 00011110 
    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

    }