将十进制转换为具有特定位数的String

时间:2014-12-09 20:55:07

标签: java string binary

这是我写的代码,但它有一些问题,我不知道 我想将十进制转换为String但具有特定的位数 但是不要使用JAVA中的内置函数

public static String convertToBinary(int decimal,int bits)
        {
        String binary ="";
        String need ="";
        int devision = decimal;
        while (devision != 0)
        {
            if(decimal%2==1)
            {
                devision = decimal/2;
                binary ='1'+binary;
            }
            if(decimal%2==0)
            {
                devision = decimal/2;
                binary='0'+binary;
            }
        }
        if(binary.length()<bits)
        {
            int diffrence = binary.length()-bits; 
            for(int i = 0;i<diffrence;i++)
            {
                need= need+'0';
            }
            binary = need + binary;
        }
        return binary;
    }

2 个答案:

答案 0 :(得分:0)

这里有两个问题。在while循环中,您只需要使用除法变量来最终将其降低到零。你拥有的是一个无限循环,因为你总是设置devision = decimal/2;

其次,要在前面添加零,您需要int diffrence = bits - binary.length();才能获得正数。

以下是修订版:

public static String convertToBinary(int decimal, int bits) {
    String binary = "";
    String need = "";
    int devision = decimal;
    while (devision > 0) {
        if (devision % 2 == 1) {
            devision /= 2;
            binary = '1' + binary;
        }
        if (devision % 2 == 0) {
            devision /= 2;
            if (devision > 0) {
                binary = '0' + binary;
            }
        }
    }
    if (binary.length() < bits) {
        int diffrence = bits - binary.length();
        for (int i = 0; i < diffrence; i++) {
            need = need + '0';
        }
        binary = need + binary;
    }
    return binary;
}

答案 1 :(得分:0)

       **convert a decimal to String with a specific number of bits**

    Scanner sc = new Scanner(System.in);
    int integer ;   
    System.out.print("Enter the binary Number: ");
    integer = sc.nextInt();

    int count = 0;
    while(integer>0)
    {
        count++;
        integer = integer >> 1;
    }
    System.out.println("Bits number : " +count);