Integer type name change.
[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 - 2001 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 /* $Id$ */
21
22 #include "silcincludes.h"
23
24 /* Encodes MP integer into binary data. Returns allocated data that
25    must be free'd by the caller. If `len' is provided the destination
26    buffer is allocated that large. If zero then the size is approximated. */
27
28 unsigned char *silc_mp_mp2bin(SilcMPInt *val, SilcUInt32 len,
29                               SilcUInt32 *ret_len)
30 {
31   int i;
32   SilcUInt32 size;
33   unsigned char *ret;
34   SilcMPInt tmp;
35
36   size = (len ? len : ((silc_mp_sizeinbase(val, 2) + 7) / 8));
37   ret = silc_calloc(size, sizeof(*ret));
38   
39   silc_mp_init(&tmp);
40   silc_mp_set(&tmp, val);
41
42   for (i = size; i > 0; i--) {
43     ret[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
44     silc_mp_div_2exp(&tmp, &tmp, 8);
45   }
46
47   silc_mp_uninit(&tmp);
48
49   if (ret_len)
50     *ret_len = size;
51
52   return ret;
53 }
54
55 /* Samve as above but does not allocate any memory.  The encoded data is
56    returned into `dst' and it's length to the `ret_len'. */
57
58 void silc_mp_mp2bin_noalloc(SilcMPInt *val, unsigned char *dst,
59                             SilcUInt32 dst_len)
60 {
61   int i;
62   SilcUInt32 size = dst_len;
63   SilcMPInt tmp;
64
65   silc_mp_init(&tmp);
66   silc_mp_set(&tmp, val);
67
68   for (i = size; i > 0; i--) {
69     dst[i - 1] = (unsigned char)(silc_mp_get_ui(&tmp) & 0xff);
70     silc_mp_div_2exp(&tmp, &tmp, 8);
71   }
72
73   silc_mp_uninit(&tmp);
74 }
75
76 /* Decodes binary data into MP integer. The integer sent as argument
77    must be initialized. */
78
79 void silc_mp_bin2mp(unsigned char *data, SilcUInt32 len, SilcMPInt *ret)
80 {
81   int i;
82
83   silc_mp_set_ui(ret, 0);
84
85   for (i = 0; i < len; i++) {
86     silc_mp_mul_2exp(ret, ret, 8);
87     silc_mp_add_ui(ret, ret, data[i]);
88   }
89 }