0

I'm trying to convert an extra large hex number to decimal number in C++.

For example:

hex: abc6a806bf5ac415016905a8de6e026c

decimal: 228329470036614264874173405720560403052

I wanna to get decimal % 60 = 52 from the example above.

I know I can do something like

int(abc6a806bf5ac415016905a8de6e026c, 16) % 60  

in python

but I don't know how to implement in C++

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Which intrinsic c++ datatype do you think can hold such big number? – πάντα ῥεῖ May 25 '22 at 21:42
  • 5
    C++ does not have a native type for integers that large. You'll need some king of *big integer* library. Googling for that should give you a few candidates. –  May 25 '22 at 21:42
  • If you are using gcc or clang you have `__int128` which is 128 bits. Other compilers might have similar https://stackoverflow.com/questions/18439520/is-there-a-128-bit-integer-in-c – Jerry Jeremiah May 25 '22 at 21:46

1 Answers1

5

You can't convert abc6a806bf5ac415016905a8de6e026c into an integer type because that will overflow.

But if all you want is x % 60 then you can perform all operations modulo 60 when converting "abc6a806bf5ac415016905a8de6e026c" to integer:

#include <string>

constexpr unsigned int to_int_mod(const std::string &hex, unsigned int m) {
    unsigned int x = 0;
    for (auto c : hex) {
        x *= 16;
        if (c >= '0' && c <= '9') {
            x += c - '0';
        } else {
            x += c - 'a' + 10;
        }
        x = x % m;
    }
    return x;
}

#include <iostream>

int main() {
    std::string hex = "abc6a806bf5ac415016905a8de6e026c";
    std::cout << hex << " % 60 = " << to_int_mod(hex, 60) << std::endl;
}
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42