Monday, June 6, 2016

Binary to Integer (Decimal) in Java

So I woke up this morning to do a daily programming challenge (first one) and thought "Let's do something easy. I'll make a binary to integer converter in java." I ended up with what I think might be the longest route to getting that done that could be possible.

Here is a short summary of how to convert binary to an integer: binary numbers are 0s and 1s. Here is one for instance. 1000. That isn't one thousand. That is actually 8 in binary. All you do is raise 2 to the power of the position that the 1s are in. The first number on the right (the right most 0) is at index 0. So for binary 1001 the first one on the right is 2^0. The left most 1 is at position 3. So it is 2^3. That gives 8 + 1 = 9. Not very complicated. (Don't forget that a number raised to the power of 0 equals one. Math!! 1000000003434234234257245^0 = 1)

For this program, we will need to follow that algorithm. We will need to get user input of a binary number and then go through each digit. But how can we get each digit in an integer? Well, first we will read the integer in. Then we will convert it to a string. That way we can treat each digit like a character and have something to work with.

Once we have the digit as a string, we can use a for loop to go through each, keeping track of where the index of the binary number is, and keep the result updated by raising 2 to the power of the index when the digit is a one. Here is the code with comments to help you see:

import java.util.Scanner;

public class BinToInt {

    public static void main(String[] args) {
        /*First create a scanner to read input then read the input*/
        Scanner read = new Scanner(System.in);  // reader for input
        System.out.println("Enter a number in binary (just use 0s and 1s): ");
        int n = read.nextInt(); // scans for user input of number
       
        //convert the int to a string so we can get each individual digit
        String number = String.valueOf(n);
        char[] digits = number.toCharArray();
       
        //find the index minus one. This will be what 2 will be raised to.
        int index = digits.length - 1;
       
        int result = 0; //for keeping track of what number we have
       
        for(char c : digits) //loop thru each char of the "int string"
        {
            int i = Integer.valueOf(String.valueOf(c)); //convert the char back to an int
            if(i == 1) //in binary, if it is a 1 it has a value
            {
                //raise 2 to the power of the index we are at
                result = result + (int)Math.pow((double)2, (double)index);
            }
            index--; //subtract from the index
        }
        System.out.println("Result: " + result); //show result

    }

}


This is probably not the fastest or simplest or easiest way to convert binary to integer, but it is dirty and it works. Greasy!

No comments:

Post a Comment