1 /* mpn_random2 -- Generate random numbers with relatively long strings
2 of ones and zeroes. Suitable for border testing.
4 Copyright (C) 1992, 1993, 1994, 1996, 2000 Free Software Foundation, Inc.
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. */
26 #if defined (__hpux) || defined (__alpha) || defined (__svr4__) || defined (__SVR4)
27 /* HPUX lacks random(). DEC OSF/1 1.2 random() returns a double. */
34 #elif defined(_WIN32) && !(defined(__CYGWIN__) || defined(__CYGWIN32__))
35 /* MS CRT supplies just the poxy rand(), with an upper bound of 0x7fff */
36 static inline unsigned long
39 return rand () ^ (rand () << 16) ^ (rand() << 32);
46 /* It's a bit tricky to get this right, so please test the code well
47 if you hack with it. Some early versions of the function produced
48 random numbers with the leading limb == 0, and some versions never
49 made the most significant bit set. */
53 mpn_random2 (mp_ptr res_ptr, mp_size_t size)
55 mpn_random2 (res_ptr, size)
68 /* Start off in a random bit position in the most significant limb. */
69 bit_pos = random () & (BITS_PER_MP_LIMB - 1);
71 /* Least significant bit of RAN chooses string of ones/string of zeroes.
72 Make most significant limb be non-zero by setting bit 0 of RAN. */
75 for (limb_pos = size - 1; limb_pos >= 0; )
77 n_bits = (ran >> 1) % BITS_PER_MP_LIMB + 1;
80 /* Generate a string of ones. */
81 if (n_bits >= bit_pos)
83 res_ptr[limb_pos--] = limb | ((((mp_limb_t) 2) << bit_pos) - 1);
84 bit_pos += BITS_PER_MP_LIMB;
85 limb = (~(mp_limb_t) 0) << (bit_pos - n_bits);
89 limb |= ((((mp_limb_t) 1) << n_bits) - 1) << (bit_pos - n_bits + 1);
94 /* Generate a string of zeroes. */
95 if (n_bits >= bit_pos)
97 res_ptr[limb_pos--] = limb;
99 bit_pos += BITS_PER_MP_LIMB;