Reputation: 21
I wrote a program to convert a number From Binary to Decimal and it is giving wrong output if the input is 0011. For 0011 answer should be 3 but it is giving 9, otherwise it is correct for other input.
Code:
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;
}
}
Upvotes: 1
Views: 178
Reputation: 24
Or Try This One Also
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);
}
}
Upvotes: 0
Reputation: 24
Try it
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;
}
}
Upvotes: 0
Reputation: 279970
An integer literal that starts with a 0
is considered to be an octal, ie. base 8.
0011
is
(0 * 8^3) + (0 * 8^2) + (1 * 8^1) + (1 * 8^0)
which is equal to 9.
0111
would be
(0 * 8^3) + (1 * 8^2) + (1 * 8^1) + (1 * 8^0)
equal to 73.
You're looking for 0b0011
which is the integer literal representation of a binary number.
Upvotes: 5
Reputation: 6887
Do it with a String like this:
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");
}
}
Upvotes: 1