5 Author: Pekka Riikonen <priikone@silcnet.org>
7 Copyright (C) 2000 - 2005 Pekka Riikonen
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; version 2 of the License.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
21 #include "silcincludes.h"
23 /* Encodes MP integer into binary data. Returns allocated data that
24 must be free'd by the caller. If `len' is provided the destination
25 buffer is allocated that large. If zero then the size is approximated. */
27 unsigned char *silc_mp_mp2bin(SilcMPInt *val, SilcUInt32 len,
35 size = (len ? len : ((silc_mp_sizeinbase(val, 2) + 7) / 8));
36 ret = silc_calloc(size, sizeof(*ret));
39 silc_mp_set(&tmp, val);
41 for (i = size; i > 0; i--) {
42 ret[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
43 silc_mp_div_2exp(&tmp, &tmp, 8);
54 /* Samve as above but does not allocate any memory. The encoded data is
55 returned into `dst' and it's length to the `ret_len'. */
57 void silc_mp_mp2bin_noalloc(SilcMPInt *val, unsigned char *dst,
61 SilcUInt32 size = dst_len;
65 silc_mp_set(&tmp, val);
67 for (i = size; i > 0; i--) {
68 dst[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
69 silc_mp_div_2exp(&tmp, &tmp, 8);
75 /* Decodes binary data into MP integer. The integer sent as argument
76 must be initialized. */
78 void silc_mp_bin2mp(unsigned char *data, SilcUInt32 len, SilcMPInt *ret)
82 silc_mp_set_ui(ret, 0);
84 for (i = 0; i < len; i++) {
85 silc_mp_mul_2exp(ret, ret, 8);
86 silc_mp_add_ui(ret, ret, data[i]);