beta-0.89.2
[luatex.git] / source / libs / gmp / gmp-src / mpz / tstbit.c
blobdb3d75a64f985c5354144c11bc738c95d65b4546
1 /* mpz_tstbit -- test a specified bit.
3 Copyright 2000, 2002 Free Software Foundation, Inc.
5 This file is part of the GNU MP Library.
7 The GNU MP Library is free software; you can redistribute it and/or modify
8 it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free Software
17 Foundation; either version 2 of the License, or (at your option) any
18 later version.
20 or both in parallel, as here.
22 The GNU MP Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
25 for more details.
27 You should have received copies of the GNU General Public License and the
28 GNU Lesser General Public License along with the GNU MP Library. If not,
29 see https://www.gnu.org/licenses/. */
31 #include "gmp.h"
32 #include "gmp-impl.h"
35 /* For negatives the effective twos complement is achieved by negating the
36 limb tested, either with a ones or twos complement. Twos complement
37 ("-") is used if there's only zero limbs below the one being tested.
38 Ones complement ("~") is used if there's a non-zero below. Note that "-"
39 is correct even if the limb examined is 0 (and the true beginning of twos
40 complement is further up).
42 Testing the limbs below p is unavoidable on negatives, but will usually
43 need to examine only *(p-1). The search is done from *(p-1) down to
44 *u_ptr, since that might give better cache locality, and because a
45 non-zero limb is perhaps a touch more likely in the middle of a number
46 than at the low end.
48 Bits past the end of available data simply follow sign of u. Notice that
49 the limb_index >= abs_size test covers u=0 too. */
51 int
52 mpz_tstbit (mpz_srcptr u, mp_bitcnt_t bit_index) __GMP_NOTHROW
54 mp_srcptr u_ptr = PTR(u);
55 mp_size_t size = SIZ(u);
56 unsigned abs_size = ABS(size);
57 mp_size_t limb_index = bit_index / GMP_NUMB_BITS;
58 mp_srcptr p = u_ptr + limb_index;
59 mp_limb_t limb;
61 if (limb_index >= abs_size)
62 return (size < 0);
64 limb = *p;
65 if (size < 0)
67 limb = -limb; /* twos complement */
69 while (p != u_ptr)
71 p--;
72 if (*p != 0)
74 limb--; /* make it a ones complement instead */
75 break;
80 return (limb >> (bit_index % GMP_NUMB_BITS)) & 1;