7

I would like to know if there is a method to convert a binary value to a decimal value?

For example, I need to convert the binary 10000101111010 and get the result 8570.

11

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.

  • 1
    Nah converting to a Decimal is easy! public static Decimal binaryToDecimal(String value) { return (Decimal)binaryToInteger(value); }. Might be worth including what the << operator does. This is just magic to most of us. – Adrian Larson Jan 17 '17 at 21:54
  • @AdrianLarson Good point... one sec. – sfdcfox Jan 17 '17 at 21:55
  • had to favorite this question for the answer :) – Rao Jan 17 '17 at 22:06
5

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.

  • 1
    Thanks for the response, I tried the two methods and it works fine. Dommage que cette méthode n'existe pas en standard. – Aurélien Laval Jan 18 '17 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.