将boost :: multiprecision实数转换为整数

时间:2013-10-02 15:04:11

标签: c++ boost g++ decimal bigdecimal

我正在尝试将boost::multiprecision::cpp_dec_float_x转换为boost::multiprecision::uintx_t。因此,对于这种转换所需的内存而言,基本上是一个提升bigint来提升bigint,而不是有损。 请考虑以下事项:

boost::multiprecision::cpp_dec_float_100 myreal(100); /* bigreal */
boost::multiprecision::uint256_t myint; /* bigint */

设计内存分配

我想从第一个到最后一个进行转换。考虑到我一直在计算所需的位数。从256位整数开始,我需要一个能够存储0到2 ^ 256-1的浮点数。我需要多少位数?完全256*log_10(2) ~= 77。所以一个100位的浮动就足够了。因此,如果我将实数保持在低于2 ^ 256,我可以将其转换为256位整数。

如何考虑convert_to<>只能用于内置类型和static_cast<>引发错误(考虑到boost documentation没有提到这样的背景,我可以进行转换) )?三江源

不关心数据丢失

我不关心数据丢失。为了我的目的,我将存储(在bigreal变量中)一个整数(没有小数部分)。所以我很好!

1 个答案:

答案 0 :(得分:0)

我不知道你是否正在寻找,试试......

cpp_dec_float_100 myreal(100);
cpp_dec_float_100 int_part = myreal.backend().extract_integer_part();

类型仍为cpp_dec_float_100,但仅包含整数部分。 我希望这会有所帮助。