Most efficient way to convert BCD to binary

Andy picture Andy · Jan 20, 2009 · Viewed 13.1k times · Source

I have the code below to convert a 32 bit BCD value (supplied in two uint halves) to a uint binary value.

The values supplied can be up to 0x9999, to form a maximum value of 0x99999999.

Is there a better (ie. quicker) way to achieve this?

    /// <summary>
    /// Convert two PLC words in BCD format (forming 8 digit number) into single binary integer.
    /// e.g. If Lower = 0x5678 and Upper = 0x1234, then Return is 12345678 decimal, or 0xbc614e.
    /// </summary>
    /// <param name="lower">Least significant 16 bits.</param>
    /// <param name="upper">Most significant 16 bits.</param>
    /// <returns>32 bit unsigned integer.</returns>
    /// <remarks>If the parameters supplied are invalid, returns zero.</remarks>
    private static uint BCD2ToBin(uint lower, uint upper)
    {
        uint binVal = 0;

        if ((lower | upper) != 0)
        {
            int shift = 0;
            uint multiplier = 1;
            uint bcdVal = (upper << 16) | lower;

            for (int i = 0; i < 8; i++)
            {
                uint digit = (bcdVal >> shift) & 0xf;

                if (digit > 9)
                {
                    binVal = 0;
                    break;
                }
                else
                {
                    binVal += digit * multiplier;
                    shift += 4;
                    multiplier *= 10;
                }
            }
        }

        return binVal;
    }

Answer

Pete Kirkham picture Pete Kirkham · Jan 21, 2009

If you've space to spare for a 39,322 element array, you could always just look the value up.