[SOLVED] How does gmp recognize a signed integer?

Issue

This Content is from Stack Overflow. Question asked by piggogo

How does gmp recognize a signed integer? When I use the gmp library, I can safely put two large positive integers or unsigned integers into the mpz_ tdiv_q () function performs division calculation, but I’m curious when I convert two 8-byte memory cells to mpz_t by using the function to convert a large negative integers, how does gmp recognize it as a negative number? Can i safely put it into the mpz_tdiv_q for division calculation?The large integer inside mpz_t stores numbers according to the complete storage unit. For example, 120 bits will occupy two consecutive 64 bit storage units. If it is a negative number at this time, do I need to expand its bit size and then use mpz_ tdiv_ q () for division calculation?

    uint64_t ext_lhs[2];
    uint64_t ext_rhs[2];
    mpn_copyi(ext_lhs, lhs, 2);
    mpn_copyi(ext_rhs, rhs, 2);
    //sign bit expansion for the highest bit,Is it unnecessary?
    if(overwidth){
        svs_sext_to_bv64x_from_bv64x(ext_lhs, 2, width, lhs, 2 - 1, overwidth);
        svs_sext_to_bv64x_from_bv64x(ext_rhs, 2, width, rhs, 2 - 1, overwidth);
    }
    mpz_t res, left, right;
    mpz_init(res);
    mpz_tdiv_q(res, mpz_roinit_n(left, ext_lhs, 2), mpz_roinit_n(right, ext_rhs, 2));



Solution

The size argument of mpz_roinit_n has 2 purposes. Its absolute value encodes the number of limbs, while its sign encodes the sign of the resulting number. The array of limbs always corresponds to a positive number there is no sign bit or 1/2-s complement.


This Question was asked in StackOverflow by piggogo and Answered by Marc Glisse It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?