Write a program for Binary to decimal conversion

13 July 2022

Write a program for Binary to decimal conversion


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

Get a binary value as input from the user and print the corresponding decimal number as the output

Input

1000

Output

8

C Program

#include <stdio.h>

void main()

{

    int  num, binary, decimal = 0, base = 1, rem;

    printf("Enter a binary  number: ");

    scanf("%d", &num); 

    binary = num;

    while (num > 0)

    {

        rem = num % 10;

        decimal = decimal + rem * base;

        num = num / 10 ;

        base = base * 2;

    }

    printf("%d", decimal);

}

C++ Program

#include <iostream>

using namespace std;

int main()

{

    int  num, binary, decimal = 0, base = 1, rem;

    cout<<"Enter a binary  number: ";

    cin>>num; 

    binary = num;

    while (num > 0)

    {

        rem = num % 10;

        decimal = decimal + rem * base;

        num = num / 10 ;

        base = base * 2;

    }

    cout<<decimal;

    return 0;

}

Java Program

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);    

System.out.print("Enter a binary number : ");

int bin = sc.nextInt();

int dec = 0;

int n = 0;  

while(bin > 0)

{

int temp = bin%10; 

dec += temp*Math.pow(2, n);  

bin = bin/10;  

n++;  

}

System.out.println(dec); 

}

}

Python Program

num = int(input("Enter binary value: "))

bin = num

dec = 0

base = 1

while num > 0:

    rem = num % 10

    dec = dec + rem * base

    num = num // 10

    base = base * 2

print(dec)


If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023
Related Articles

Ask Us Anything !