### 5.11 Logical and Bit Manipulation Functions

These functions behave as if two’s complement arithmetic were used (although sign-magnitude is the actual implementation). The least significant bit is number 0.

Function: `void` mpz_and `(mpz_t rop, const mpz_t op1, const mpz_t op2)`

Set rop to op1 bitwise-and op2.

Function: `void` mpz_ior `(mpz_t rop, const mpz_t op1, const mpz_t op2)`

Set rop to op1 bitwise inclusive-or op2.

Function: `void` mpz_xor `(mpz_t rop, const mpz_t op1, const mpz_t op2)`

Set rop to op1 bitwise exclusive-or op2.

Function: `void` mpz_com `(mpz_t rop, const mpz_t op)`

Set rop to the one’s complement of op.

Function: `mp_bitcnt_t` mpz_popcount `(const mpz_t op)`

If op>=0, return the population count of op, which is the number of 1 bits in the binary representation. If op<0, the number of 1s is infinite, and the return value is the largest possible `mp_bitcnt_t`.

Function: `mp_bitcnt_t` mpz_hamdist `(const mpz_t op1, const mpz_t op2)`

If op1 and op2 are both >=0 or both <0, return the hamming distance between the two operands, which is the number of bit positions where op1 and op2 have different bit values. If one operand is >=0 and the other <0 then the number of bits different is infinite, and the return value is the largest possible `mp_bitcnt_t`.

Function: `mp_bitcnt_t` mpz_scan0 `(const mpz_t op, mp_bitcnt_t starting_bit)`
Function: `mp_bitcnt_t` mpz_scan1 `(const mpz_t op, mp_bitcnt_t starting_bit)`

Scan op, starting from bit starting_bit, towards more significant bits, until the first 0 or 1 bit (respectively) is found. Return the index of the found bit.

If the bit at starting_bit is already what’s sought, then starting_bit is returned.

If there’s no bit found, then the largest possible `mp_bitcnt_t` is returned. This will happen in `mpz_scan0` past the end of a negative number, or `mpz_scan1` past the end of a nonnegative number.

Function: `void` mpz_setbit `(mpz_t rop, mp_bitcnt_t bit_index)`

Set bit bit_index in rop.

Function: `void` mpz_clrbit `(mpz_t rop, mp_bitcnt_t bit_index)`

Clear bit bit_index in rop.

Function: `void` mpz_combit `(mpz_t rop, mp_bitcnt_t bit_index)`

Complement bit bit_index in rop.

Function: `int` mpz_tstbit `(const mpz_t op, mp_bitcnt_t bit_index)`

Test bit bit_index in op and return 0 or 1 accordingly.

Shifting is also possible using multiplication (Arithmetic Functions) and division (Division Functions), in particular the `2exp` functions.