xref: /plan9/sys/src/cmd/unix/drawterm/libmp/mpright.c (revision 8ccd4a6360d974db7bd7bbd4f37e7018419ea908)
1 #include "os.h"
2 #include <mp.h>
3 #include "dat.h"
4 
5 // res = b >> shift
6 void
mpright(mpint * b,int shift,mpint * res)7 mpright(mpint *b, int shift, mpint *res)
8 {
9 	int d, l, r, i;
10 	mpdigit this, last;
11 
12 	// a negative right shift is a left shift
13 	if(shift < 0){
14 		mpleft(b, -shift, res);
15 		return;
16 	}
17 
18 	if(res != b)
19 		mpbits(res, b->top*Dbits - shift);
20 	d = shift/Dbits;
21 	r = shift - d*Dbits;
22 	l = Dbits - r;
23 
24 	// special case digit shifts
25 	if(r == 0){
26 		for(i = 0; i < b->top-d; i++)
27 			res->p[i] = b->p[i+d];
28 	} else {
29 		last = b->p[d];
30 		for(i = 0; i < b->top-d-1; i++){
31 			this = b->p[i+d+1];
32 			res->p[i] = (this<<l) | (last>>r);
33 			last = this;
34 		}
35 		res->p[i++] = last>>r;
36 	}
37 	while(i > 0 && res->p[i-1] == 0)
38 		i--;
39 	res->top = i;
40 }
41