1 /* mpz_hamdist -- calculate hamming distance.
3 Copyright 1994, 1996, 2001, 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 the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or (at your
10 option) any later version.
12 The GNU MP Library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/. */
25 mpz_hamdist (mpz_srcptr u, mpz_srcptr v)
28 mp_size_t usize, vsize;
40 return ~ (mp_bitcnt_t) 0;
42 /* positive/positive */
45 MPN_SRCPTR_SWAP (up,usize, vp,vsize);
49 count = mpn_hamdist (up, vp, vsize);
53 count += mpn_popcount (up + vsize, usize);
59 mp_limb_t ulimb, vlimb;
60 mp_size_t old_vsize, step;
63 return ~ (mp_limb_t) 0;
65 /* negative/negative */
70 /* skip common low zeros */
87 MPN_SRCPTR_SWAP (up,usize, vp,vsize);
94 /* twos complement first non-zero limbs (ulimb is non-zero, but vlimb
98 popc_limb (count, (ulimb ^ vlimb) & GMP_NUMB_MASK);
102 mp_bitcnt_t twoscount;
104 /* first non-zero of v */
114 /* part of u corresponding to skipped v zeros */
115 step = old_vsize - vsize - 1;
116 count += step * GMP_NUMB_BITS;
117 step = MIN (step, usize);
120 count -= mpn_popcount (up, step);
125 /* First non-zero vlimb as twos complement, xor with ones
126 complement ulimb. Note -v^(~0^u) == (v-1)^u. */
133 popc_limb (twoscount, vlimb);
137 /* Overlapping part of u and v, if any. Ones complement both, so just
139 step = MIN (usize, vsize);
142 count += mpn_hamdist (up, vp, step);
149 /* Remaining high part of u or v, if any, ones complement but xor
150 against all ones in the other, so plain popcount. */
154 count += mpn_popcount (up, usize);