Extracting bits from boost multiprecision

随声附和 提交于 2019-12-24 01:05:52

问题


I'm using uint256_t to make arithmetic operation on big integers; I would like to extract the bits of the numbers in a regular form, (i.e. not in a floating point form) without any precision since I'm only using integers and not floats.

For example: if my code has:

#include <boost/multiprecision/cpp_int.hpp>    
uint256_t v = 0xffffffffffffffffffffffffffffff61;

Then I would like to have 32 bytes:

61 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

回答1:


You might be able to use the backend representation directly.

Check the documentation whether this is part of the public API.

Live On Coliru

#include <boost/multiprecision/cpp_int.hpp>
#include <iostream>

int main() {
    using namespace boost::multiprecision;
    uint256_t v("0xffffffffffffffffffffffffffffff61");

    std::copy_n(v.backend().limbs(), v.backend().size(), 
        std::ostream_iterator<unsigned>(std::cout << std::hex << std::showbase, " "));
}

Prints

0xffffff61 0xffffffff 

Drop std::showbase to do without 0x. I picked this representation so it's maximally clear how the limbs are grouped.




回答2:


You cannot have directly what you ask. Internal rapresentation is not necessarily done that way, one type uses even 'decimal' digits.

You can obtain that indirectly

uint256_t v = 0xffffffffffffffffffffffffffffff61;
std::ostringstream ost ;
ost << std::hex << v ; 

now ost.str() is FFFF....FFF61



来源:https://stackoverflow.com/questions/36037686/extracting-bits-from-boost-multiprecision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!