libtommath/mp_set_double.c

48 lines
1.4 KiB
C
Raw Normal View History

2018-09-10 16:51:26 +00:00
#include "tommath_private.h"
#ifdef 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) || defined(__x86_64__) || defined(_M_X64) || defined(_M_AMD64) || defined(__i386__) || defined(_M_X86) || defined(__aarch64__) || defined(__arm__)
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);
2019-11-06 10:52:42 +00:00
frac = (cast.bits & (((uint64_t)1 << 52) - (uint64_t)1)) | ((uint64_t)1 << 52);
2018-09-10 16:51:26 +00:00
if (exp == 0x7FF) { /* +-inf, NaN */
return MP_VAL;
}
exp -= 1023 + 52;
2019-05-24 08:21:54 +00:00
mp_set_u64(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-11-06 10:29:17 +00:00
if (((cast.bits >> 63) != 0u) && !mp_iszero(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