Skip to content

Instantly share code, notes, and snippets.

@moritz
Created November 8, 2011 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moritz/1349237 to your computer and use it in GitHub Desktop.
Save moritz/1349237 to your computer and use it in GitHub Desktop.
Preliminary mp_int -> double conversion
#include "tommath.h"
#include <stdlib.h>
#include <math.h>
double mp_get_double(mp_int *a) {
double d = 0.0;
if (USED(a) == 0)
return d;
if (USED(a) == 1)
return SIGN(a) == MP_NEG ? (double) -mp_get_int(a) : (double) mp_get_int(a);
int i;
for (i = USED(a) - 1; DIGIT(a, i) == 0 && i > 0; i--) {
/* do nothing */
}
d = (double) DIGIT(a, i);
if (SIGN(a) == MP_NEG)
d *= -1;
i--;
if (i == -1) {
return d;
}
d *= pow(2.0, DIGIT_BIT);
d += (double) DIGIT(a, i);
d *= pow(2.0, DIGIT_BIT * i);
return d;
}
int main(void) {
mp_int *b;
mp_init(b);
mp_set_int(b, 12);
mp_mul_2d(b, 130, b);
double d = mp_get_double(b);
printf("%.10e\n", d);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment