1 /* mpz_setbit -- set a specified bit.
3 Copyright (C) 1991, 1993, 1994, 1995, 1997, 1999 Free Software Foundation,
6 This file is part of the GNU MP Library.
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 2.1 of the License, or (at your
11 option) any later version.
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.
18 You should have received a copy of the GNU Lesser General Public License
19 along with the GNU MP Library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21 MA 02111-1307, USA. */
28 mpz_setbit (mpz_ptr d, unsigned long int bit_index)
30 mpz_setbit (d, bit_index)
32 unsigned long int bit_index;
35 mp_size_t dsize = d->_mp_size;
39 limb_index = bit_index / BITS_PER_MP_LIMB;
42 if (limb_index < dsize)
44 dp[limb_index] |= (mp_limb_t) 1 << (bit_index % BITS_PER_MP_LIMB);
49 /* Ugh. The bit should be set outside of the end of the
50 number. We have to increase the size of the number. */
51 if (d->_mp_alloc < limb_index + 1)
53 _mpz_realloc (d, limb_index + 1);
56 MPN_ZERO (dp + dsize, limb_index - dsize);
57 dp[limb_index] = (mp_limb_t) 1 << (bit_index % BITS_PER_MP_LIMB);
58 d->_mp_size = limb_index + 1;
65 /* Simulate two's complement arithmetic, i.e. simulate
66 1. Set OP = ~(OP - 1) [with infinitely many leading ones].
68 3. Set OP = ~OP + 1. */
72 /* No upper bound on this loop, we're sure there's a non-zero limb
74 for (zero_bound = 0; ; zero_bound++)
75 if (dp[zero_bound] != 0)
78 if (limb_index > zero_bound)
80 if (limb_index < dsize)
81 dp[limb_index] &= ~((mp_limb_t) 1 << (bit_index % BITS_PER_MP_LIMB));
85 else if (limb_index == zero_bound)
87 dp[limb_index] = ((dp[limb_index] - 1)
88 & ~((mp_limb_t) 1 << (bit_index % BITS_PER_MP_LIMB))) + 1;
89 if (dp[limb_index] == 0)
92 for (i = limb_index + 1; i < dsize; i++)
98 /* We got carry all way out beyond the end of D. Increase
99 its size (and allocation if necessary). */
101 if (d->_mp_alloc < dsize)
103 _mpz_realloc (d, dsize);
107 d->_mp_size = -dsize;
113 mpn_decr_u (dp + limb_index,
114 (mp_limb_t) 1 << (bit_index % BITS_PER_MP_LIMB));
115 dsize -= dp[dsize - 1] == 0;
116 d->_mp_size = -dsize;