Search code examples
c++radixbase-conversionternary-representation

Convert decimal to balanced Heptavintimal


I'm trying to make a function to convert decimal to balanced Heptavintimal (0123456789ABCDEFGHKMNPRTVXZ) where 0 represent -13, D : 0 and Z 13

I have tried this but some cases are not working properly:

static const std::string HEPT_CHARS = "0123456789ABCDEFGHKMNPRTVXZ";

std::string heptEnc(int value){
    std::string result = "";

    do {
        int pos = value % 27;
        result = std::string(HEPT_CHARS[(pos + 13)%27] + result);
        value = value / 27;
    } while (value != 0);

    return result;
}

Here is what I get in this example -14, -15, 14, 15 isn't working

call(x) - expect: result
heptEnc(-9841) - 000: 000
heptEnc(-15) - CX: 
heptEnc(-14) - CZ: 
heptEnc(-13) - 0: 0
heptEnc(-1) - C: C
heptEnc(0) - D: D
heptEnc(1) - E: E
heptEnc(13) - Z: Z
heptEnc(14) - E0: 0
heptEnc(15) - E1: 1
heptEnc(9841) - ZZZ: ZZZ 

Solution

  • Just got it working, here is the code:

    static const std::string HEPT_CHARS = "0123456789ABCDEFGHKMNPRTVXZ";
    
    inline int modulo(int a, int b) 
    {
        const int result = a % b;
        return result >= 0 ? result : result + b;
    }
    
    std::string heptEnc(int value)
    {
        std::string result = "";
    
        do {
            int pos = value%27;
            result = std::string(HEPT_CHARS[modulo(pos + 13,27)] + result);
            value = (value+pos) / 27;
        } while (value != 0);
    
        return result;
    }
    

    Apparently a mix of mathematical modulo, C++ modulo and modifying the way you update your value did the trick.