Java while loop convert binary number to decimal number

Question

We would like to use while loop to convert binary number to decimal number

public class Main {
  public static void main(String[] args) {
    int binary = 0; // original binary
    int decimal = 0; // conversion
    int place = 0; // the 2's place

    binary = 0B10;/*from   w w  w  .  ja v  a 2  s  . com*/

    //your code here

    System.out.printf("%d = %d\n", binary, decimal);
  }
}



public class Main {
  public static void main(String[] args) {
    int binary = 0; // original binary
    int decimal = 0; // conversion
    int place = 0; // the 2's place

    binary = 0B10;

    while (binary != 0) {
      // extract rightmost digit
      int lastDigit = binary % 10;

      // raise rightmost digit to 2^place and add to decimal
      decimal += lastDigit * Math.pow(2, place);

      // slice rightmost digit from original
      binary /= 10;

      // shift 2's place to the left
      place++;
    }

    System.out.printf("%d = %d\n", binary, decimal);
  }
}



PreviousNext

Related