c++ – Fastest way to convert from unsigned integer + scale to double

With a compile time precalculated scale table it would look like this :

#include <array>
#include <cstdint>
#include <cmath>
#include <iostream>

// I use int8_t instead of char since char can be 
// signed or unsigned dependent on platform

namespace init
{
    // https://en.cppreference.com/w/cpp/language/constexpr
    constexpr auto create_power_table()
    {
        // fill an array with 1e-128 to 1e128 values
        std::array<double, 256ul> powers{};
        
        double value = 1.0;
        for (std::size_t n = 0; n < 128; ++n)
        {
            powers[128 - n] = value;
            value /= 10.0;
        }

        value = 1.0;
        for (std::size_t n = 0; n < 127; ++n)
        {
            powers[128 + n] = value;
            value *= 10.0;
        }

        return powers;
    }
}

// create a compile time table with double scale values
constexpr std::array<double, 256> power_table = init::create_power_table();

constexpr double convert(std::int64_t value, std::int8_t scale)
{
    // calculate the index in the table
    std::size_t index = static_cast<std::size_t>(scale) + 128ul;
    return static_cast<double>(value) * power_table[index];
};


int main()
{
    std::cout << convert(1, -120) << "\n";
    std::cout << convert(1, -1) << "\n";
    std::cout << convert(1, 1) << "\n";
    std::cout << convert(1, 2) << "\n";
    std::cout << convert(1, 120) << "\n";
    
    return 0;
}

Read more here: Source link