1 /* mpz_setbit -- set a specified bit.
3 Copyright 1991, 1993-1995, 1997, 1999, 2001, 2002, 2012 Free Software
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 either:
11 * the GNU Lesser General Public License as published by the Free
12 Software Foundation; either version 3 of the License, or (at your
13 option) any later version.
17 * the GNU General Public License as published by the Free Software
18 Foundation; either version 2 of the License, or (at your option) any
21 or both in parallel, as here.
23 The GNU MP Library is distributed in the hope that it will be useful, but
24 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
25 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
28 You should have received copies of the GNU General Public License and the
29 GNU Lesser General Public License along with the GNU MP Library. If not,
30 see https://www.gnu.org/licenses/. */
36 mpz_setbit (mpz_ptr d
, mp_bitcnt_t bit_idx
)
38 mp_size_t dsize
= SIZ (d
);
43 limb_idx
= bit_idx
/ GMP_NUMB_BITS
;
44 mask
= CNST_LIMB(1) << (bit_idx
% GMP_NUMB_BITS
);
53 /* Ugh. The bit should be set outside of the end of the
54 number. We have to increase the size of the number. */
55 dp
= MPZ_REALLOC (d
, limb_idx
+ 1);
56 SIZ (d
) = limb_idx
+ 1;
57 MPN_ZERO (dp
+ dsize
, limb_idx
- dsize
);
63 /* Simulate two's complement arithmetic, i.e. simulate
64 1. Set OP = ~(OP - 1) [with infinitely many leading ones].
66 3. Set OP = ~OP + 1. */
73 /* No index upper bound on this loop, we're sure there's a non-zero limb
76 while (dp
[zero_bound
] == 0)
79 if (limb_idx
> zero_bound
)
82 dlimb
= dp
[limb_idx
] & ~mask
;
85 if (UNLIKELY ((dlimb
== 0) + limb_idx
== dsize
)) /* dsize == limb_idx + 1 */
87 /* high limb became zero, must normalize */
88 MPN_NORMALIZE (dp
, limb_idx
);
92 else if (limb_idx
== zero_bound
)
94 dp
[limb_idx
] = ((dp
[limb_idx
] - 1) & ~mask
) + 1;
95 ASSERT (dp
[limb_idx
] != 0);
99 MPN_DECR_U (dp
+ limb_idx
, dsize
- limb_idx
, mask
);
100 dsize
-= dp
[dsize
- 1] == 0;