libtommath/bn_mp_set_double.c

48 lines
1.2 KiB
C
Raw Normal View History

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)
mp_err mp_set_double(mp_int *a, double b)
2018-09-10 16:51:26 +00:00
{
uint64_t frac;
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
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;
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
}
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
/* pragma message() not supported by several compilers (in mostly older but still used versions) */
# 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