2018-09-10 16:51:26 +00:00
|
|
|
#include "tommath_private.h"
|
|
|
|
#ifdef BN_MP_SET_DOUBLE_C
|
2019-04-07 13:29:11 +00:00
|
|
|
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
|
|
|
|
/* SPDX-License-Identifier: Unlicense */
|
2018-09-10 16:51:26 +00:00
|
|
|
|
|
|
|
#if defined(__STDC_IEC_559__) || defined(__GCC_IEC_559)
|
2019-05-12 22:22:18 +00:00
|
|
|
mp_err mp_set_double(mp_int *a, double b)
|
2018-09-10 16:51:26 +00:00
|
|
|
{
|
|
|
|
uint64_t frac;
|
2019-05-12 22:22:18 +00:00
|
|
|
int exp;
|
2019-05-19 15:16:13 +00:00
|
|
|
mp_err err;
|
2018-09-10 16:51:26 +00:00
|
|
|
union {
|
|
|
|
double dbl;
|
|
|
|
uint64_t bits;
|
|
|
|
} cast;
|
2018-11-28 09:46:12 +00:00
|
|
|
cast.dbl = b;
|
2018-09-10 16:51:26 +00:00
|
|
|
|
2019-05-19 14:36:53 +00:00
|
|
|
exp = (int)((unsigned)(cast.bits >> 52) & 0x7FFu);
|
|
|
|
frac = (cast.bits & ((1uLL << 52) - 1uLL)) | (1uLL << 52);
|
2018-09-10 16:51:26 +00:00
|
|
|
|
|
|
|
if (exp == 0x7FF) { /* +-inf, NaN */
|
|
|
|
return MP_VAL;
|
|
|
|
}
|
|
|
|
exp -= 1023 + 52;
|
|
|
|
|
2019-05-10 21:59:46 +00:00
|
|
|
mp_set_long_long(a, frac);
|
2018-09-10 16:51:26 +00:00
|
|
|
|
2019-05-19 15:16:13 +00:00
|
|
|
err = (exp < 0) ? mp_div_2d(a, -exp, a, NULL) : mp_mul_2d(a, exp, a);
|
|
|
|
if (err != MP_OKAY) {
|
|
|
|
return err;
|
2018-12-01 07:35:22 +00:00
|
|
|
}
|
|
|
|
|
2019-05-19 14:36:53 +00:00
|
|
|
if (((cast.bits >> 63) != 0uLL) && !MP_IS_ZERO(a)) {
|
2018-12-27 17:04:25 +00:00
|
|
|
a->sign = MP_NEG;
|
2018-09-10 16:51:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return MP_OKAY;
|
|
|
|
}
|
|
|
|
#else
|
2018-12-07 20:18:43 +00:00
|
|
|
/* pragma message() not supported by several compilers (in mostly older but still used versions) */
|
2018-12-07 19:47:51 +00:00
|
|
|
# ifdef _MSC_VER
|
|
|
|
# pragma message("mp_set_double implementation is only available on platforms with IEEE754 floating point format")
|
|
|
|
# else
|
|
|
|
# warning "mp_set_double implementation is only available on platforms with IEEE754 floating point format"
|
|
|
|
# endif
|
2018-09-10 16:51:26 +00:00
|
|
|
#endif
|
|
|
|
#endif
|