简体   繁体   中英

How to convert an extra larger hex number to decimal number in C++

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++

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM