简体   繁体   中英

How to convert a large string number (uint256) into vector<unsigned char> in C++

I have a string number ranging in uint256, such as "115792089237316195423570985008687907853269984665640564039457584007913129639935". And I want to store this number into the vector<unsigned char> in C++. That is, I want to get 0xffffff...fff (255bit) stored in the vector.

I have tried the following ways:\
1)Using int to receive the string number and transfer, but the number is out of the int range.\
2)Using boost::multiprecision::number<boost::multiprecision::cpp_int_backend<256, 256, boost::multiprecision::unsigned_magnitude, boost::multiprecision::unchecked, void>>. But I do not know how to transfer the string number to this type. I cannot find the details of using this type on the internet.

This Boost.Multiprecision-based solution worked for me well:

std::string input { "115792089237316195423570985008687907853269984665640564039457584007913129639935" };

boost::multiprecision::uint256_t i { input };

std::stringstream ss;
ss << std::hex << i;
std::string s = ss.str();
std::cout << s << std::endl;

std::vector<unsigned char> v{s.begin(), s.end()};    

It prints:

ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff

Is it what you are looking for?

Live demo: https://godbolt.org/z/cW1hf61Wf .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM