Assigning 128 bit integer in C

前端 未结 3 2042
天命终不由人
天命终不由人 2020-12-01 18:08

When I try to assign an 128 bit integer in gcc 4.9.1, I get a warning: integer constant is too large for its type.

Example Code

int ma         


        
3条回答
  •  执念已碎
    2020-12-01 18:35

    Have you tried this?

    __int128 p = *(__int128*) "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";
    

    EDIT Nov. 25

    Sorry for the poor clarification on previous post. Seriously, I didn't post this answer as a joke. Though the GCC doc states there's no way to express a 128-bit integer constant, this post simply provides a workaround for those who wants to assign values to __uint128_t variables with ease.

    You may try to comile the code below with GCC (7.2.0) or Clang (5.0.0). It prints desired results.

    #include 
    #include 
    
    int main()
    {
        __uint128_t p = *(__int128*) "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";
        printf("HIGH %016llx\n", (uint64_t) (p >> 64));
        printf("LOW  %016llx\n", (uint64_t) p);
        return 0;
    }
    

    The stdout:

    HIGH 0f0e0d0c0b0a0908
    LOW  0706050403020100
    

    This is only regarded as a workaround since it plays tricks on pointers by placing the "value" in .rodata section (if you objdump it), and it's not portable (x86_64 and aarch64 are fine but not arm and x86). I think it's been enough for those coding on desktop machines.

提交回复
热议问题