十进制到二进制8位仅使用append

时间:2013-08-21 04:12:52

标签: java binary

我在将十进制转换为二进制时遇到问题。如何使用字符串生成器从一开始就添加0来转换二进制文件?

while (num != 0){    
  int digit = num % 2;

  buf.append(digit);
  num = num/2;
}   

System.out.println(num);

5 个答案:

答案 0 :(得分:1)

通过将数字除以2并记下余数,可以将十进制数转换为二进制数   例如,如果您将12作为十进制数,则二进制数将为1100

手动输出:

2 12

2 6 0

2 3 0

2 1 1

1

将十进制转换为二进制的代码是

class Binary
    {
        public StringBuffer calBinary(int decnum){

          StringBuffer sBuf = new StringBuffer();
               int temp=0;
               while(decnum>0){
                      temp = decnum%2;
                      sBuf.append(temp);
                     decnum = decnum / 2;
               }
         return sBuf.reverse();
   } }  


 public class Sri {

   public static void main(String[] args) throws IOException {
    System.out.println(" please enter the decimal number to convert into binary");
    BufferedReader br = new   BufferedReader(new InputStreamReader(System.in));
    int num = Integer.parseInt(br.readLine());

    Binary K = new Binary();
    StringBuffer result = K.calBinary(decnum);
    System.out.println(result);
              }
 }

答案 1 :(得分:1)

尝试使用字符串构建器类中的reverse()方法。有点像:

buf = buf.reverse();

答案 2 :(得分:1)

你可以试试这个

        int num=10;
    StringBuilder buf1=new StringBuilder();
    StringBuilder buf2=new StringBuilder();
    while (num != 0){
        int digit = num % 2;
        buf1.append(digit); // apend 0101 order
        num = num/2;
    }
    String binary=buf1.reverse().toString();// reverse to get binary 1010
    int length=binary.length();
    if(length<8){
       while (8-length>0){
           buf2.append("0");// add zero until length =8
           length++;
       }
    }
    String bin=buf2.toString()+binary;// binary string with leading 0's
    System.out.println(bin);

现场演示here

Out put

00001010

您可以使用数组执行相同操作,如下所示

    int num=10;
    int[] binArr=new int[8];
    int j=0;
    while (num != 0){
        int digit = num % 2;
        binArr[binArr.length-1-j]=digit;
        num = num/2;
        j++;
    }
    System.out.println(Arrays.toString(binArr).replaceAll("\\,|\\[|\\]",""));

答案 3 :(得分:1)

试试这个(对原始代码进行最少的修改)......

    int num=8;
    StringBuilder buf = new StringBuilder();
    while (num != 0){    
          int digit = num % 2;

          buf.append(digit);
          num = num/2;
        }   

        System.out.println(buf.reverse());

答案 4 :(得分:-1)

如果你只允许追加,你可能应该使用递归:

String toBinaryString(int num)
{
    StringBuilder sb = new StringBuilder();
    if (num > 1)
    {
        sb.append(decimalToBinary(num/2));    // or num >> 1
    }
    sb.append((num & 1));
    return sb.toString();
}

不是世界上效率最高的代码,但您确实指定了StringBuilder和仅附加。处理负数作为读者的练习。