1import java.util.Scanner;
2public class BinaryToDecimalDemo
3{
4 public static void main(String[] args)
5 {
6 int number, decimal = 0, a = 0;
7 Scanner sc = new Scanner(System.in);
8 System.out.println("Please enter binary number: ");
9 String strBinary = sc.nextLine();
10 number = Integer.parseInt(strBinary);
11 while(number != 0){
12 decimal += (number % 10) * Math.pow(2, a);
13 number = number / 10;
14 a++;
15 }
16 System.out.println("Decimal number: " + decimal);
17 sc.close();
18 }
19}
1#include <math.h>
2#include <stdio.h>
3int convert(long long n);
4int main() {
5 long long n;
6 printf("Enter a binary number: ");
7 scanf("%lld", &n);
8 printf("%lld in binary = %d in decimal", n, convert(n));
9 return 0;
10}
11
12int convert(long long n) {
13 int dec = 0, i = 0, rem;
14 while (n != 0) {
15 rem = n % 10;
16 n /= 10;
17 dec += rem * pow(2, i);
18 ++i;
19 }
20 return dec;
21}
22
1double binaryToDecimal(char binary[DIM]) {
2 char binary2[DIM] = "", floa[DIM] = "";
3 double decimal = 0, negDec = 0, flo = 0;
4 int count = 0, j = 0, i = 0, f = 0, g = 0, h = 0, count1 = 0, d = 0, k = 0;
5 while (binary[d] != '\0'&&binary[d] != '.') { d++; }
6 d--;
7 if (binary[0] == '-') {
8 while (binary[k] != '\0') {
9 binary[k] = binary[k + 1];
10 k++;
11 }
12 k = 0;
13 while (binary[k] == '0') {
14 d--;
15 k++;
16 }
17 negDec = pot(2.000, d*1.000, 1);
18 }
19 while (binary[i] != '\0'&&binary[i] != '.') {
20 i++;
21 }
22 i--;
23 count = i;
24 h = i;
25 while (binary[h] != '\0') {
26 floa[g] = binary[h + 2];
27 g++;
28 h++;
29 }
30 g--;
31 count1 = g;
32 while (i >= 0) {
33 binary2[j] = binary[i];
34 i--;
35 j++;
36 }
37 binary2[j] = '\0';
38 while (i <= count) {
39 if (binary2[i] == '1') {
40 decimal = decimal + pot(2.000, i, 1);
41 }
42 i++;
43 }
44 h = -1;
45 g = 0;
46 while (g <= count1) {
47 if (floa[g] == '1') {
48 flo = flo + pot(2.000, h, 1);
49 }
50 g++;
51 h--;
52 }
53 decimal = decimal + flo;
54 if (negDec > 0) {
55 decimal = (decimal - negDec);
56 if (flo > 0) {
57 double f = fl(decimal);
58 f = 1 - f;
59 decimal = returnDeciPart(decimal) - f;
60 }
61 }
62 return decimal;
63}
1import java.util.Scanner;
2
3public class BinaryToDecimal {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 Scanner sc = new Scanner(System.in);
8 String binary = sc.next();
9 // This is one line solution for binary to decimal in java
10 System.out.println(Integer.parseInt(binary,2));
11
12 //This solution is based on formula for binary to decimal conversion
13 int n=0,dec=0;
14 for(int i=binary.length()-1;i>=0;i--)
15 {
16 dec = dec + Integer.parseInt(String.valueOf(binary.charAt(i)))*(int)Math.pow(2,n);
17 n++;
18 }
19 System.out.println(dec);
20
21 }
22
23}
24