1 /* mpz_clrbit -- clear a specified bit. 2 3 Copyright 1991, 1993, 1994, 1995, 2001, 2002, 2012 Free Software Foundation, 4 Inc. 5 6 This file is part of the GNU MP Library. 7 8 The GNU MP Library is free software; you can redistribute it and/or modify 9 it under the terms of the GNU Lesser General Public License as published by 10 the Free Software Foundation; either version 3 of the License, or (at your 11 option) any later version. 12 13 The GNU MP Library is distributed in the hope that it will be useful, but 14 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY 15 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public 16 License for more details. 17 18 You should have received a copy of the GNU Lesser General Public License 19 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */ 20 21 #include "gmp.h" 22 #include "gmp-impl.h" 23 24 void 25 mpz_clrbit (mpz_ptr d, mp_bitcnt_t bit_idx) 26 { 27 mp_size_t dsize = SIZ (d); 28 mp_ptr dp = PTR (d); 29 mp_size_t limb_idx; 30 mp_limb_t mask; 31 32 limb_idx = bit_idx / GMP_NUMB_BITS; 33 mask = CNST_LIMB(1) << (bit_idx % GMP_NUMB_BITS); 34 if (dsize >= 0) 35 { 36 if (limb_idx < dsize) 37 { 38 mp_limb_t dlimb; 39 dlimb = dp[limb_idx]; 40 dlimb &= ~mask; 41 dp[limb_idx] = dlimb; 42 43 if (UNLIKELY (dlimb == 0 && limb_idx == dsize-1)) 44 { 45 /* high limb became zero, must normalize */ 46 MPN_NORMALIZE (dp, limb_idx); 47 SIZ (d) = limb_idx; 48 } 49 } 50 else 51 ; 52 } 53 else 54 { 55 mp_size_t zero_bound; 56 57 /* Simulate two's complement arithmetic, i.e. simulate 58 1. Set OP = ~(OP - 1) [with infinitely many leading ones]. 59 2. clear the bit. 60 3. Set OP = ~OP + 1. */ 61 62 dsize = -dsize; 63 64 /* No index upper bound on this loop, we're sure there's a non-zero limb 65 sooner or later. */ 66 zero_bound = 0; 67 while (dp[zero_bound] == 0) 68 zero_bound++; 69 70 if (limb_idx > zero_bound) 71 { 72 if (limb_idx < dsize) 73 dp[limb_idx] |= mask; 74 else 75 { 76 /* Ugh. The bit should be cleared outside of the end of the 77 number. We have to increase the size of the number. */ 78 dp = MPZ_REALLOC (d, limb_idx + 1); 79 SIZ (d) = -(limb_idx + 1); 80 MPN_ZERO (dp + dsize, limb_idx - dsize); 81 dp[limb_idx] = mask; 82 } 83 } 84 else if (limb_idx == zero_bound) 85 { 86 dp[limb_idx] = ((((dp[limb_idx] - 1) | mask) + 1) & GMP_NUMB_MASK); 87 if (dp[limb_idx] == 0) 88 { 89 /* Increment at limb_idx + 1. Extend the number with a zero limb 90 for simplicity. */ 91 dp = MPZ_REALLOC (d, dsize + 1); 92 dp[dsize] = 0; 93 MPN_INCR_U (dp + limb_idx + 1, dsize - limb_idx, 1); 94 dsize += dp[dsize]; 95 96 SIZ (d) = -dsize; 97 } 98 } 99 else 100 ; 101 } 102 } 103