How to initialize an _Extint() from an hardcoded litteral?

229 Views Asked by At

The rust project I m using depends on fixed_hash 0.2.2. And I would need to compare one H160 against a literal (mode exactly know if my_var==0xdac17f958d2ee523a2206206994597c13d831ec7).

Internally, the H160 type is just a pointer to a plain integer encoded like with _Extint(). And as I already need to pass the value to a C module, I m thinking about just making the comparison from there.

The problem is integer litterals in clang are read as 64 bits Integers, so that

const _ExtInt(160) my_const=0xdac17f958d2ee523a2206206994597c13d831ec7;

fails with

<source>:1:28: error: integer literal is too large to be represented in any integer type

So how to assign 0xdac17f958d2ee523a2206206994597c13d831ec7 to my_const in big endian?

2

There are 2 best solutions below

11
KamilCuk On

Construct it from smaller values and shift.

const _ExtInt(160) my_const = 
    (unsigned _ExtInt(160))0xdac17f95ull << 128 |
    (unsigned _ExtInt(160))0x8d2ee523a2206206ull << 64 |
    (unsigned _ExtInt(160))0x994597c13d831ec7ull << 0;
2
Aykhan Hagverdili On

You can add a routine to parse it from a string. In C++, this can be done at compile time:

#include <stdexcept>

template <class T>
constexpr auto parseInt(const char* str) {
    T res = 0;
    while (*str) {
        const char ch = *str++;
        if (ch < '0' || ch > '9') {
            throw std::runtime_error("String does not represent an int");
        }
        res *= 10;
        res += (ch - '0');
    }
    return res;
}

int main() {
    constexpr auto my_const = parseInt<unsigned _BitInt(160)>("1248875146012964071876423320777688075155124985543");
}