How can I add and subtract 128 bit integers in C or C++ if my compiler does not support them?

后端 未结 7 738
我在风中等你
我在风中等你 2020-11-28 11:07

I\'m writing a compressor for a long stream of 128 bit numbers. I would like to store the numbers as differences -- storing only the difference between the numbers rather th

7条回答
  •  一整个雨季
    2020-11-28 11:50

    Take a look at GMP.

    #include 
    #include 
    
    int main (int argc, char** argv) {
        mpz_t x, y, z;
        char *xs, *ys, *zs;
        int i;
        int base[4] = {2, 8, 10, 16};
    
        /* setting the value of x in base 10 */
        mpz_init_set_str(x, "100000000000000000000000000000000", 10);
    
        /* setting the value of y in base 16 */
        mpz_init_set_str(y, "FF", 16);
    
        /* just initalizing the result variable */
        mpz_init(z);
    
        mpz_sub(z, x, y);
    
        for (i = 0; i < 4; i++) {
            xs = mpz_get_str(NULL, base[i], x);
            ys = mpz_get_str(NULL, base[i], y);
            zs = mpz_get_str(NULL, base[i], z);
    
            /* print all three in base 10 */
            printf("x = %s\ny = %s\nz = %s\n\n", xs, ys, zs);
    
            free(xs);
            free(ys);
            free(zs);
        }
    
        return 0;
    }
    

    The output is

    x = 10011101110001011010110110101000001010110111000010110101100111011111000000100000000000000000000000000000000
    y = 11111111
    z = 10011101110001011010110110101000001010110111000010110101100111011111000000011111111111111111111111100000001
    
    x = 235613266501267026547370040000000000
    y = 377
    z = 235613266501267026547370037777777401
    
    x = 100000000000000000000000000000000
    y = 255
    z = 99999999999999999999999999999745
    
    x = 4ee2d6d415b85acef8100000000
    y = ff
    z = 4ee2d6d415b85acef80ffffff01
    

提交回复
热议问题