0
Sponsored Links


Ad by Google
Java coding practice and sometimes asked in core Java written interview question. For freshers it's important to do practice on such coding exercise like how to balanced parentheses and finding factorial of a given number.
In this article, i'm going to show two simple way to convert binary values into decimal numbers, in previous post, I had shared the just op positive how to convert decimal to binary here.

package com.javamakeuse.poc;

/**
 * 
 * @author javamakeuse
 *
 */
public class BinaryToDecimal {

 // converting binary to decimal via parseInt method
 public static void binaryToDecimal(String binary) {
  System.out.println(Integer.parseInt(binary, 2));
 }

 // converting binary to decimal via custom implementation
 public static void binaryToDecimal2(String binary) {
  double j = 0;
  for (int i = 0; i < binary.length(); i++) {
   if (binary.charAt(i) == '1') {
    j = j + Math.pow(2, binary.length() - 1 - i);
   }

  }
  System.out.println((int) j);
 }

 public static void main(String[] args) {
  binaryToDecimal("10001100");
  binaryToDecimal2("10001100");
 }
}

OUTPUT:
140
140

Sponsored Links

0 comments:

Post a Comment