Convert a binary value to an decimal value

Converting to an Integer or Long value is fairly trivial:

public static Integer binaryToInteger(String value) {
    Integer result;
    if(value != null && value.containsOnly('01')) {
        result = 0;
        for(String s: value.split('')) {
            result = (result << 1) | (s == '1'? 1: 0);
        }
    }
    return result;
}

(You can replace Integer above with Long to get more bit storage).

You can also cast the result to a Decimal, but it will still only be a whole number. If you want to include proper decimal values, on the other hand, you'll have to parse IEEE 754 bits, which is a little more complicated than a simple shift/or loop.


Basically, this method first creates a buffer of all binary 0 values. For each bit in the string, it shifts all the bits left 1 (<< 1), and then binary ORs (|) the latest bit into position. Basically, we're reading the string from left to right to build the number in decimal notation.

N.B. Older versions of the API included a blank space in the first array index when you split an empty string. I've adjusted this code (after thinking about it) so that a blank string is also interpreted as a 0 bit, so this code should work in any class regardless of API version.


First of all, sfdcfox's answer is awesome and I have learnt much from it. But if you want to avoid the magical bitwise operators, here is a simplified version which does exactly the same thing. Actually, it is just translated from sfdcfox's code:

public static Integer binaryToInteger(String value) {
    Integer result;
    if(value != null && value.containsOnly('01')) {
        result = 0;
        for(String s: value.split('')) {
            result *= 2;
            result += (s == '1'? 1: 0); 
        }
    }
    return result;
}

This is just an adding to fox's answer to help you understand that more easily.

Tags:

Apex

Convert