Page 229 - ARM 64 Bit Assembly Language
P. 229
Integer mathematics 217
146 bigint_free(tmp1);
147 tmp1 = tmp2;
148 }
149 for (i = tmp1->size-1; i >= 0; i--)
150 result |= (tmp1->blks[i]<<(i*BITSPERCHUNK));
151 bigint_free(tmp1);
152 if (negative)
153 result = -result;
154 return result;
155 }
156
157 /* convert a bigint to a string */
158 char *bigint_to_str(bigint b) {
159 int negative = 0;
160 unsigned remainder;
161 char *s, *r;
162 bigint tmp, tmp2;
163 /* rough estimate of the number of characters needed */
164 int chars = log10(pow(2.0, (b->size * BITSPERCHUNK)))+3;
165 int i = chars-1;
166 if ((s = (char*)malloc(1 + chars * sizeof(char))) == NULL) {
167 perror("bigint_str");
168 exit(1);
169 }
170 s[i] = 0; /* set last character to ASCII null */
171 tmp = bigint_copy(b);
172 if (b->blks[tmp->size-1] & ((bigchunk)1<< (BITSPERCHUNK-1))) {
173 negative = 1;
174 tmp2 = bigint_negate(tmp);
175 bigint_free(tmp);
176 tmp = tmp2;
177 }
178 if (bigint_is_zero(tmp)) {
179 s[--i] = ’0’;
180 } else {
181 do {
182 remainder = bigint_smallmod(tmp, 10);
183 s[--i] = remainder + ’0’;
184 } while(!bigint_is_zero(tmp));
185 if (negative)
186 s[--i] = ’-’;
187 }
188 r = strdup(s + i);
189 bigint_free(tmp);
190 free(s);
191 return r;
192 }
193
194 /* destroy a bigint */