xref: /plan9/sys/src/libmp/port/betomp.c (revision 9027b8f78b93f49ddfe75d1dcbf015f5ad6582b6)
1 #include "os.h"
2 #include <mp.h>
3 #include "dat.h"
4 
5 // convert a big-endian byte array (most significant byte first) to an mpint
6 mpint*
betomp(uchar * p,uint n,mpint * b)7 betomp(uchar *p, uint n, mpint *b)
8 {
9 	int m, s;
10 	mpdigit x;
11 
12 	if(b == nil){
13 		b = mpnew(0);
14 		setmalloctag(b, getcallerpc(&p));
15 	}
16 
17 	// dump leading zeros
18 	while(*p == 0 && n > 1){
19 		p++;
20 		n--;
21 	}
22 
23 	// get the space
24 	mpbits(b, n*8);
25 	b->top = DIGITS(n*8);
26 	m = b->top-1;
27 
28 	// first digit might not be Dbytes long
29 	s = ((n-1)*8)%Dbits;
30 	x = 0;
31 	for(; n > 0; n--){
32 		x |= ((mpdigit)(*p++)) << s;
33 		s -= 8;
34 		if(s < 0){
35 			b->p[m--] = x;
36 			s = Dbits-8;
37 			x = 0;
38 		}
39 	}
40 
41 	return b;
42 }
43