binary to decimal

In this article, we are going to see how we can convert binary to decimal. We also write java code to convert binary to decimal.

Binary to Decimal conversion:-

Steps:-

  • Take a variable to hold the decimal result.
  • Take a variable power and initialize it with 0.
  • Create a loop to Iterate binary number from right to left.
  • Now calculate the value number *(2^power).
  • add the value into the result variable.
  • increase power by 1.
  • End of loop.
  • result variable will be hold the result value of binary.

Java code to convert binary to decimal:-

package gangforcode;
import java.util.*;
public class binaryToDecimal {
	public static void binToDec(String s) {
		int m=0;
		int k=1;
		for(int i=s.length()-1;i>=0;i--) {
			m+= (s.charAt(i)-'0')*k;
			k=k*2;
			
		}
		System.out.println(m);
			}

	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		System.out.println("Enter the binary string");
		String s=sc.nextLine();
		binToDec(s);
		
	}

}

Output:-

binary to decimal

The same logic can be used to convert binary to decimal in other programing languages like C, C++, Python, etc.

Java code to convert binary to decimal video

Leave a Comment