URI:
       tmptole.c - plan9port - [fork] Plan 9 from user space
  HTML git clone git://src.adamsgaard.dk/plan9port
   DIR Log
   DIR Files
   DIR Refs
   DIR README
   DIR LICENSE
       ---
       tmptole.c (796B)
       ---
            1 #include "os.h"
            2 #include <mp.h>
            3 #include "dat.h"
            4 
            5 /* convert an mpint into a little endian byte array (least significant byte first) */
            6 
            7 /*   return number of bytes converted */
            8 /*   if p == nil, allocate and result array */
            9 int
           10 mptole(mpint *b, uchar *p, uint n, uchar **pp)
           11 {
           12         int i, j;
           13         mpdigit x;
           14         uchar *e, *s;
           15 
           16         if(p == nil){
           17                 n = (b->top+1)*Dbytes;
           18                 p = malloc(n);
           19         }
           20         if(pp != nil)
           21                 *pp = p;
           22         if(p == nil)
           23                 return -1;
           24         memset(p, 0, n);
           25 
           26         /* special case 0 */
           27         if(b->top == 0){
           28                 if(n < 1)
           29                         return -1;
           30                 else
           31                         return 0;
           32         }
           33 
           34         s = p;
           35         e = s+n;
           36         for(i = 0; i < b->top-1; i++){
           37                 x = b->p[i];
           38                 for(j = 0; j < Dbytes; j++){
           39                         if(p >= e)
           40                                 return -1;
           41                         *p++ = x;
           42                         x >>= 8;
           43                 }
           44         }
           45         x = b->p[i];
           46         while(x > 0){
           47                 if(p >= e)
           48                         return -1;
           49                 *p++ = x;
           50                 x >>= 8;
           51         }
           52 
           53         return p - s;
           54 }