4

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 
YesThatIsMyName
  • 1,585
  • 3
  • 23
  • 30
Jeremy Talus
  • 125
  • 2
  • 11

2 Answers2

3

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.

sirandy
  • 1,834
  • 5
  • 27
  • 32
Elias
  • 56
  • 7
  • indeed mathimatical trick, and since I doind calculation and paper, so my calculator use Math modulo and not c++ modulo anyway thanks – Jeremy Talus May 16 '19 at 15:15
1

You're using mod (%) incorrectly. It's difficult/complicated to know what a signed int will initially be set to. So try this instead:

unsigned int uvalue = std::abs(value);
unsigned int upos = uvalue % 27;
int pos = static_cast<int>(upos) - 13;

Of course you'll have to deal with the sign of your conversion separately:

int sign = value >= 0 ? 1 : -1;
Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • in fact it's not a problem of sign. more a problem around `value = value / 27;` the problem is the balanced system, since 0 represet -13 and Z +13 so E0 ca be read as 27 + -13 so it's 14 – Jeremy Talus May 16 '19 at 14:50