将 java 中的十进制数转换为二进制数不显示前导零

Converting a decimal number to binary in java not showing leading zeroes

这是我在Java中的功能:

public static String convertFromDecimal(int number, int base)
    {

        String result = "";

        /*
         * This while loop will keep running until 'number' is not 0
         */

        while(number != 0)
        {
            result = (number%base) + result; // Appending the remainder
            number = number / base; // Dividing the number by the base so we can get the next remainder
        }

        // If the number is already 0, then the while loop will ignore it, so we will return "0"

        if(result == "") 
        {
            return "0";
        }

        return result;

    }

对于转换为不以0开头的数字的数字工作正常,如果数字应该在开头为零,它不会记录它,谁能告诉我为什么?

例如,如果我打印出来

convertFromDecimal(13,2)这returns

1101

这是正确的,但如果我打印出来

convertFromDecimal(461,2), 我得到

111001101

实际答案是

0000000111001101

所以它和我的答案一样没有前导零,如果有人知道为什么我会很感激帮助,谢谢。

EDIT 我的问题是不同的,因为我不想要 16 位数字,我想要给定十进制的二进制数,像 this 这样的计算器可以解释什么我要。

我假设您希望将所有答案格式化为短裤(16 位)。

在这种情况下,只需检查当前字符串的长度,并根据需要添加零。

int zeroesRemaining = 16 - result.length();
for (int i = 0; i < zeroesRemaining; i++) {
    result = "0" + result;
}

或者,如果您想更快地完成,请使用 StringBuilder。

int zeroesRemaining = 16 - result.length();
StringBuilder tempBuilder = new StringBuilder(result);
for (int i = 0; i < zeroesRemaining; i++) {
    tempBuilder.insert(0, 0); //inserts the integer 0 at position 0 of the stringbuilder
}
return tempBuilder.toString(); //converts to string format

可能还有一个格式化程序可以执行此操作,但我不知道。

如果您想将零的数量更改为最接近的整数基元,只需将​​ zeroesRemaining 设置为(大于位数的 2 的最小幂)减去(位数)。

由于您希望结果的长度固定,以 8 位为一组,最简单的方法是将 0 附加到 result 的前面,直到其长度为 8 的倍数。

就这么简单

wile (result.length() % 8 > 0) 
{
    result = "0" + result;
}
return result;