Binary to Decimal java conversion

This is a simple Java implementation of Binary to Decimal number conversion.


Simple Java implementation

public static int bin2dec(String binary) {
    int result = 0;
    for (int i = 0; i < binary.length(); i++) {
        int n = binary.charAt(i) - '0';
        result = result * 2 + n;
    }
    return result;
}

Usage

bin2dec("0");   // 0
bin2dec("1");   // 1
bin2dec("10");  // 2
bin2dec("11");  // 3
bin2dec("100"); // 4
bin2dec("101"); // 5
bin2dec("110"); // 6
bin2dec("111"); // 7

Standard implementation

Since Java 1.8, core class Integer contains a very convenient method for parsing unsigned integers:

Integer.parseUnsignedInt("0", 2);   // 0
Integer.parseUnsignedInt("1", 2);   // 1
Integer.parseUnsignedInt("10", 2);  // 2
Integer.parseUnsignedInt("11", 2);  // 3
Integer.parseUnsignedInt("100", 2); // 4
Integer.parseUnsignedInt("101", 2); // 5
Integer.parseUnsignedInt("110", 2); // 6
Integer.parseUnsignedInt("111", 2); // 7

Also, there is a method for parsing any (signed) integer:

public static int parseInt(String s) throws NumberFormatException {...}

Complete example

/**
 * @author Denis Migol
 */
public class BinaryToDecimalExample {
    public static int bin2dec(String binary) {
        int result = 0;
        for (int i = 0; i < binary.length(); i++) {
            int n = binary.charAt(i) - '0';
            result = result * 2 + n;
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(bin2dec("0"));   // 0
        System.out.println(bin2dec("1"));   // 1
        System.out.println(bin2dec("10"));  // 2
        System.out.println(bin2dec("11"));  // 3
        System.out.println(bin2dec("100")); // 4
        System.out.println(bin2dec("101")); // 5
        System.out.println(bin2dec("110")); // 6
        System.out.println(bin2dec("111")); // 7

        System.out.println(Integer.parseUnsignedInt("0", 2));   // 0
        System.out.println(Integer.parseUnsignedInt("1", 2));   // 1
        System.out.println(Integer.parseUnsignedInt("10", 2));  // 2
        System.out.println(Integer.parseUnsignedInt("11", 2));  // 3
        System.out.println(Integer.parseUnsignedInt("100", 2)); // 4
        System.out.println(Integer.parseUnsignedInt("101", 2)); // 5
        System.out.println(Integer.parseUnsignedInt("110", 2)); // 6
        System.out.println(Integer.parseUnsignedInt("111", 2)); // 7
    }
}