简体   繁体   中英

How to convert a binary String to a decimal string in Java

I was working on a homework and thought I had finished but the teacher told me that it wasn't what he was looking for so I need to know how I can convert a binary number that is stored as a String to a decimal string without using any built-in function outside of length(), charAt(), power function, and floor/ceiling in Java.

This is what I had on the beginning.

import java.util.Scanner;

public class inclass2Fall15Second {
    public static void convertBinaryToDecimalString() {
        Scanner myscnr = new Scanner(System.in);

        int decimal = 0;

        String binary;
        System.out.println("Please enter a binary number: ");
        binary = myscnr.nextLine();
        decimal = Integer.parseInt(binary, 2);
        System.out.println("The decimal number that corresponds to " + binary + " is " + decimal);
    }

    public static void main (String[] args) {
        convertBinaryToDecimalString();
    }
}

To convert a base 2 (binary) representation to base 10 (decimal), multiply the value of each bit with 2^(bit position) and sum the values.

eg 1011 -> (1 * 2^0) + (1 * 2^1) + (0 * 2^2) + (1 * 2^3) = 1 + 2 + 0 + 8 = 11

Since binary is read from right-to-left (ie LSB (least significant bit) is on the rightmost bit and MSB (most-significant-bit) is the leftmost bit), we traverse the string in reverse order.

To get the bit value, subtract '0' from the char. This will subtract the ascii value of the character with the ascii value of '0', giving you the integer value of the bit.

To calculate 2^(bit position), we can keep a count of the bit position, and increment the count on each iteration. Then we can just do 1 << count to obtain the value for 2 ^ (bit position). Alternatively, you could do Math.pow(2, count) as well, but the former is more efficient, since its just a shift-left instruction.

Here's the code that implements the above:

public static int convertBinStrToInt(String binStr) {
    int dec = 0, count = 0;
    for (int i = binStr.length()-1; i >=0; i--) {
        dec += (binStr.charAt(i) - '0') * (1 << count++);
    }

    return dec;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM