### Java Program to Convert Binary to Decimal - The Coding Shala

Hey there, welcome back to another post. In this post, we will learn how to convert Binary to Decimal in Java.

## Java Program to Convert Binary to Decimal

You have given a binary number, convert it to a decimal number.

**Example: **

```
Input: 101
Output: 5
Input: 111
Output: 7
```

## Binary to Decimal Conversion in Java

**Approach**

We will the below formula to convert binary to decimal:

decimal number = (2^0) * (rightmost digit) + (2^1) * (second rightmost digit) + ...

for example:

binary number = 110 decimal number = 2^0 * 0 + 2^1 * 1 + 2^2 * 1 = 1 * 0 + 2 * 1 + 4 * 1 = 0 + 2 + 4 = 6

**Java Program: **

import java.util.Scanner; /** * https://www.thecodingshala.com/ */ public class Main { public static void printDecimal(int num) { int decimal = 0; int twos = 1; // 2^0 = 1 initial value while (num > 0) { int temp = num % 10; decimal += temp * twos; twos = twos * 2; num = num / 10; } System.out.println(decimal); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a binary number, should only contains 0 and 1s"); int num = sc.nextInt(); System.out.println("The decimal of " + num + " is: "); printDecimal(num); } }

**Output: **

Enter a binary number, should only contains 0 and 1s 110 The decimal of 110 is: 6

**Other Posts You May Like**

- Java Program to Convert Decimal to Binary
- Java Program to Convert int to double
- Java Program to Convert double to int
- Java Program to Convert int to long
- Java Program to Convert long to int

Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

So, there's a single zero area and a double zero area – you will see these two fields as you play on-line American roulette for cash. This version is far more prevalent in America, and you're 코인카지노 likely to to|prone to} find it in an American land-based casino. The double-zero area implies that the percentages of winning might be slightly decrease for the player, unlike to|not like} the European version of the sport. The on-line Roulette video games are similar to the traditional ones, except that the variety of colors and the variety of slots for each colour could be totally different.

ReplyDelete