Created. MP integer binary encoding/decoding functions.
[silc.git] / lib / silcmath / mpbin.c
1 /*
2
3   mpbin.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 2000 Pekka Riikonen
8
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; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20
21 #include "silcincludes.h"
22
23 /* Encodes MP integer into binary data. Returns allocated data that
24    must be free'd by the caller. */
25
26 unsigned char *silc_mp_mp2bin(SilcInt *val, unsigned int *ret_len)
27 {
28   int i;
29   unsigned int size;
30   unsigned char *ret;
31   SilcInt tmp;
32
33   size = (silc_mp_sizeinbase(val, 2) + 7) / 8;
34   ret = silc_calloc(size, sizeof(*ret));
35
36   silc_mp_init_set(&tmp, val);
37
38   for (i = size; i > 0; i--) {
39     ret[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
40     silc_mp_fdiv_q_2exp(&tmp, &tmp, 8);
41   }
42
43   silc_mp_clear(&tmp);
44
45   if (*ret_len)
46     *ret_len = size;
47
48   return ret;
49 }
50
51 /* Decodes binary data into MP integer. The integer sent as argument
52    must be initialized. */
53
54 void silc_mp_bin2mp(unsigned char *data, unsigned int len, SilcInt *ret)
55 {
56   int i;
57
58   silc_mp_set_ui(ret, 0);
59
60   for (i = 0; i < len; i++) {
61     silc_mp_mul_2exp(ret, ret, 8);
62     silc_mp_add_ui(ret, ret, data[i]);
63   }
64 }