Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write an application that inputs an integer containing only 0\'s and 1\'s(i.e. b

ID: 3609365 • Letter: W

Question

Write an application that inputs an integer containing only 0's and 1's(i.e. binary integer) and prints its decimal equivalent.[Hint: use the remainder and division operators to pick off the binary number's digits one at a time, from right to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next digit to the left has a positional value of 10, then 100, then 1000, and so on. The decimal number 234 can be interpreted as 4*1 + 3*10 +2*100. In the binary number system, the rightmost digit has a positional value of 1, the next digit to the left has a positional value 2, then 4, then 8, and so on. The decimal equivalent of binary 1101 is 1*1 + 0*2 + 1*4 + 1*8, or 1 + 0 + 4 + 8, or 13.]

Explanation / Answer

import java.util.*;
public class binarytodecimal
{public static void main(String[]args)
{int i,done;
long num,sum,to=10,digit,from=2;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number to convert(negative to exit):");
num=in.nextInt();

while(num!=-1)
{ sum=0;
i=0;
System.out.print(num + " in base "+from+" is: ");
while(num>0)
   {digit=num%to;
   num=num/to;
   sum+=digit*Math.pow(from,i);
   i++;
   }
  
    System.out.println(sum + " in base "+to);
    System.out.print("Enter the number toconvert(negative to exit):");
    num=in.nextInt();
    }   
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote