aboutsummaryrefslogtreecommitdiff
path: root/src/libmp/port/mptobe.c
blob: e08ae56bebbb9c14819a5b7b34160a03a334577a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include "os.h"
#include <mp.h>
#include "dat.h"

// convert an mpint into a big endian byte array (most significant byte first)
//   return number of bytes converted
//   if p == nil, allocate and result array
int
mptobe(mpint *b, uchar *p, uint n, uchar **pp)
{
	int i, j, suppress;
	mpdigit x;
	uchar *e, *s, c;

	if(p == nil){
		n = (b->top+1)*Dbytes;
		p = malloc(n);
	}
	if(p == nil)
		return -1;
	if(pp != nil)
		*pp = p;
	memset(p, 0, n);

	// special case 0
	if(b->top == 0){
		if(n < 1)
			return -1;
		else
			return 1;
	}
		
	s = p;
	e = s+n;
	suppress = 1;
	for(i = b->top-1; i >= 0; i--){
		x = b->p[i];
		for(j = Dbits-8; j >= 0; j -= 8){
			c = x>>j;
			if(c == 0 && suppress)
				continue;
			if(p >= e)
				return -1;
			*p++ = c;
			suppress = 0;
		}
	}

	// guarantee at least one byte
	if(s == p){
		if(p >= e)
			return -1;
		*p++ = 0;
	}

	return p - s;
}