Search code examples
c++hex

C++ uint16_t to hex


I use some constants, and I need to except magic numbers in my code such as:

static const uint16_t val = 0x7076
static const uint16_t val_tag = 7076
....

So i have to declare above static uint16_t MAGIC_NUMBER_VAL = 7076 and when use this here:

static const uint16_t val = convert_func(MAGIC_NUMBER_VAL); //0x7076
static const uint16_t val_tag = MAGIC_NUMBER_VAL;

What the best way to convert uint to hex? What the convert_func most be?

p.s preferably this func most be built_in


Solution

  • If your constant can be made constexpr you can just write a constexpr function to do the "conversion"

    constexpr uint16_t convert_func(uint16_t x) {
        uint16_t acc = 0;
    
        int p10 = 1;
        int p16 = 1;
        for(int i = 0; i != 5; ++i) {
            acc += ((x / p10) % 10) * p16;
            p10 *= 10;
            p16 *= 16;
        }
    
        return acc;
    } 
     
    static constexpr uint16_t MAGIC_NUMBER_VAL = 7076;
     
    static constexpr uint16_t val = convert_func(MAGIC_NUMBER_VAL);
    static constexpr uint16_t val_tag = MAGIC_NUMBER_VAL;
    
    static_assert(val == 0x7076);