二进制到十进制的程序在Java代码中给出错误

时间:2013-12-20 06:38:53

标签: java

我编写了一个程序,用于将数字从二进制转换为十进制,如果输入为0011,则输出错误。对于0011,应该是3,但它给出9,否则对其他输入是正确的。

代码:

public class BinaryToDecimal {
static int testcase1=1001;
public static void main(String[] args) {
    BinaryToDecimal test = new BinaryToDecimal();
    int result = test.convertBinaryToDecimal(testcase1);
    System.out.println(result);
}   
//write your code here
public int convertBinaryToDecimal(int binary) {
    int powerOfTwo=1,decimal=0;
    while(binary>0)
    {
        decimal+=(binary%10)*powerOfTwo;
        binary/=10;
        powerOfTwo*=2;
    }
    return decimal;
}
}

4 个答案:

答案 0 :(得分:5)

0开头的整数文字被认为是八进制,即。基地8。

0011 

(0 * 8^3) + (0 * 8^2) + (1 * 8^1) + (1 * 8^0)

等于9。

0111 

将是

(0 * 8^3) + (1 * 8^2) + (1 * 8^1) + (1 * 8^0)

等于73。

您正在寻找0b0011,它是二进制数的整数文字表示。

答案 1 :(得分:1)

使用像这样的字符串:

public static void main(String[] args) throws IOException 
{  
    boolean correctInput = true;
    BufferedReader m_bufRead = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Bitte geben sie eine Dualzahl ein:");
    String input = m_bufRead.readLine().trim();
    for(int i = 0; i < input.length(); i++) {
        if(input.charAt(i)!='0' && input.charAt(i)!='1') {
            correctInput = false;
        }
    }
    if(correctInput) {
        long dezimal = 0;
        for(int i = 0; i < input.length(); i++) {
            dezimal += Character.getNumericValue(input.charAt(i)) * Math.pow(2, input.length()-(i+1));
        }
        System.out.println("\nDezimalwert:\n" + dezimal);
    }
    else {
        System.out.println("Ihre Eingabe kann nicht umgewandelt werden");
    }
}

答案 2 :(得分:0)

试试吧

public class Binary2Decimal
{
public static void main(String arg[])
{
    int sum=0,len,e, d, c;
    int a[]=new int[arg.length];

    for(int i=0; i<=(arg.length-1); i++)
    {
        a[i]=Integer.parseInt(arg[i]);        // Enter every digits i.e 0 or 1, with space 
    }
    len=a.length;
    d=len;
    for(int j=0; j<d; j++)
    {
        len--;
        e=pow(2,len);
        System.out.println(e);
        c=a[j]*e;
        sum=sum+c;
    }
    System.out.println("sum is " +sum);
}

static int pow(int c, int d)
{       
            int n=1;
    for(int i=0;i<d;i++)
    {
      n=c*n;
    }
    return n;
}
 }

答案 3 :(得分:0)

或者试试这个

import java.lang.*;
import java.io.*;

public class BinaryToDecimal{
 public static void main(String[] args) throws IOException{
BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter the Binary value: ");
  String str = bf.readLine();
  long num = Long.parseLong(str);
  long rem;
  while(num > 0){
  rem = num % 10;
  num = num / 10;
  if(rem != 0 && rem != 1){
  System.out.println("This is not a binary number.");
  System.out.println("Please try once again.");
  System.exit(0);
  }
  }
  int i= Integer.parseInt(str,2);
  System.out.println("Decimal:="+ i);
  }
        }