How to create a 128 bit integer literal

  • A+
Category:Languages

I have an integer literal in format 0x75f17d6b3588f843b13dea7c9c324e51. Is there a way to avoid compile syntax error "integer literal is too large to be represented in any integer type"?

Because I know I can work with those kind of types (I'm using uint128_t of the EOS library and if I manually insert it, it works).

Is there a way to somehow parse this string directly into the exact same integer in run time?

 


You may write a raw literal operator (a kind of user-defined literal, since C++11) for 128-bit integer.

A raw literal operator takes a single const char* as parameter. You can than write a function body to parse the string.

For example:

// Use __uint128_t for demonstration. constexpr __uint128_t operator""__uint128_t(const char* x) {     __uint128_t y = 0;     for (int i = 2; x[i] != '/0'; ++i)     {         y *= 16ull;         if ('0' <= x[i] && x[i] <= '9')             y += x[i] - '0';         else if ('A' <= x[i] && x[i] <= 'F')             y += x[i] - 'A' + 10;         else if ('a' <= x[i] && x[i] <= 'f')             y += x[i] - 'a' + 10;     }     return y; } 

Obviously, this implementation is problematic because I'm too lazy to develop a full solution, it only support hexadecimal, it does not check illegal characters such as GHIJK, etc. And it requires C++14 relaxed constexpr function. But it demonstrates that you can actually parse this string directly into the exact same integer.

Let's test it out:

int main() {     auto abc = 0x1234567890ABCDEFfedcba0987654321__uint128_t;     std::uint64_t higher = abc >> 64;     std::uint64_t lower = abc;     std::cout << std::hex << higher << ' ' << lower; } 

http://coliru.stacked-crooked.com/a/2cfab1635a1fa695

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: