Welcome to the CSC Q&A, where you can get help (and share your knowledge) about computer science!

Does anyone have an algorithm for converting binary numbers to a base 10 number?

+5 votes
asked Aug 24, 2016 in CSC 211 (F16) by Alyssa Nestor (100 points)

2 Answers

+2 votes

My simplest algorithm is:  Take the binary number (e.g. 1011) and write down the place value underneath each number.

1     1    0    1    1
16s 8s  4s  2s  1s

Then add up all the place values that have a 1 in them.  

16 + 8 + 2 + 1 = 27

11011 (base 2) = 27 (base 10)

This page gives a more detailed tutorial:  http://www.electronics-tutorials.ws/binary/bin_2.html

Note that there's quite a bit more information in that tutorial than what you need to know for our class.  (e.g. it does conversions both ways).

 

answered Aug 25, 2016 by Forrest Stonedahl (100 points)
0 votes
Try this:
 

import java.io.Console;
import java.util.Scanner;

public class BinaryConverter
{
    public static void main(String[] args)
    {
        System.out.print("Please type in the number you want to convert: ");
        Scanner sc = new Scanner(System.in);

        int a = sc.nextInt(), b;
        String result = a % 2 + "";
        
        while (a / 2 != 0)
        {
            a = a / 2;
            b = a % 2;
            result = b + result;
        }
        System.out.println(result);
    }

}
answered Aug 25, 2016 by Minh Ta (100 points)
P/S: the algorithm is dividing the number by 2, and the remainder will be the left binary digit.
I believe the OP was asking for an algorithm in the sense of a sequence of steps that a *human* would perform -- not actual computer code.
Also, this code would convert a base 10 number INTO binary -- not the other way around!
...