c++boostbignum

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". I want to store the bytes of this number into a vector<unsigned char>. That is, I want to get 0xffffff...fff (256bit) stored in the vector, where the vector's size will not be larger than 32 bytes.

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.


Solution

  • 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.

    EDIT

    I might have originally misunderstood the question. If you want the vector to contain the binary representation of that number (that is to serialize that number into a vector), it is also possible, and even easier:

    std::string input{ "115792089237316195423570985008687907853269984665640564039457584007913129639935" };
    boost::multiprecision::uint256_t i { input };
        
    std::vector<unsigned char> v;
    export_bits(i, std::back_inserter(v), 8);
    

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

    Corresponding documentation: https://www.boost.org/doc/libs/1_65_0/libs/multiprecision/doc/html/boost_multiprecision/tut/import_export.html.