3 Bignum operations that are missing from gmp.
5 Copyright (C) 2001 Niels Möller
7 This file is part of GNU Nettle.
9 GNU Nettle is free software: you can redistribute it and/or
10 modify it under the terms of either:
12 * the GNU Lesser General Public License as published by the Free
13 Software Foundation; either version 3 of the License, or (at your
14 option) any later version.
18 * the GNU General Public License as published by the Free
19 Software Foundation; either version 2 of the License, or (at your
20 option) any later version.
22 or both in parallel, as here.
24 GNU Nettle is distributed in the hope that it will be useful,
25 but WITHOUT ANY WARRANTY; without even the implied warranty of
26 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27 General Public License for more details.
29 You should have received copies of the GNU General Public License and
30 the GNU Lesser General Public License along with this program. If
31 not, see http://www.gnu.org/licenses/.
43 /* Two's complement negation means that -x = ~x + 1, ~x = -(x+1),
44 * and we use that x = ~~x = ~(-x-1).
56 /* Including extra sign bit, if needed. Also one byte for zero. */
58 nettle_mpz_sizeinbase_256_s(const mpz_t x)
61 return 1 + mpz_sizeinbase(x, 2) / 8;
64 /* We'll output ~~x, so we need as many bits as for ~x */
69 mpz_com(c, x); /* Same as c = - x - 1 = |x| + 1 */
70 size = 1 + mpz_sizeinbase(c,2) / 8;
78 nettle_mpz_sizeinbase_256_u(const mpz_t x)
80 return (mpz_sizeinbase(x,2) + 7) / 8;
84 nettle_mpz_to_octets(size_t length, uint8_t *s,
85 const mpz_t x, uint8_t sign)
87 uint8_t *dst = s + length - 1;
88 size_t size = mpz_size(x);
91 for (i = 0; i<size; i++)
93 mp_limb_t limb = mpz_getlimbn(x, i);
96 for (j = 0; length && j < sizeof(mp_limb_t); j++)
98 *dst-- = sign ^ (limb & 0xff);
105 memset(s, sign, length);
109 nettle_mpz_get_str_256(size_t length, uint8_t *s, const mpz_t x)
120 assert(nettle_mpz_sizeinbase_256_u(x) <= length);
121 nettle_mpz_to_octets(length, s, x, 0);
129 assert(nettle_mpz_sizeinbase_256_u(c) <= length);
130 nettle_mpz_to_octets(length, s, c, 0xff);
136 /* Converting from strings */
138 /* mpz_import was introduced in GMP-4.1 */
139 #define nettle_mpz_from_octets(x, length, s) \
140 mpz_import((x), (length), 1, 1, 0, 0, (s))
143 nettle_mpz_set_str_256_u(mpz_t x,
144 size_t length, const uint8_t *s)
146 nettle_mpz_from_octets(x, length, s);
150 nettle_mpz_init_set_str_256_u(mpz_t x,
151 size_t length, const uint8_t *s)
154 nettle_mpz_from_octets(x, length, s);
158 nettle_mpz_set_str_256_s(mpz_t x,
159 size_t length, const uint8_t *s)
167 nettle_mpz_from_octets(x, length, s);
173 mpz_init_set_ui(t, 1);
174 mpz_mul_2exp(t, t, length*8);
181 nettle_mpz_init_set_str_256_s(mpz_t x,
182 size_t length, const uint8_t *s)
185 nettle_mpz_set_str_256_s(x, length, s);