Konwersja na raw binary uint256_t

0

Mam pewien wynik programu, który jest 256-bitowym intem z biblioteki boost. Próbuję go przekonwertować na format binarny, ale podejrzewam, że coś jest nie tak.

uint256_t result;

std::cout.write(reinterpret_cast<char*>(&result), sizeof result);

Wyniki nie zdają testów, a powinny. Podejrzewam, że uint256_t jest za duży, żeby to przekonwertować w ten sposób, ale na czym polega błąd - nie wiem.

Mogę to rozwiązać tak:

unsigned __int128 a = (unsigned __int128)result;
uint256_t b = result >> 128;
unsigned __int128 c = (unsigned __int128)b;
        

std::cout.write(reinterpret_cast<char*>(&a), sizeof a);
std::cout.write(reinterpret_cast<char*>(&c), sizeof c);

Wziąć górne i dolne 128 bitów mojego result i zapisać je jako unsigned __int128. To działa. Ale czy jest jakiś bardziej elegancki sposób, żeby tyle nie kombinować i za jednym zamachem przekonwertować całego 256-bitowego inta?

1

reinterpret_cast głupieje, bo próbuje reinterpretować coś, co nie jest polem bitowym ani niczym „normalnym”, tylko taką strukturą:

typedef unspecified-type limb_type;

template <std::size_t MinBits = 0,
          std::size_t MaxBits = 0,
          cpp_integer_type SignType = signed_magnitude,
          cpp_int_check_type Checked = unchecked,
          class Allocator = std::allocator<limb_type>
class cpp_int_backend;

typedef number<cpp_int_backend<256, 256, unsigned_magnitude, unchecked, void> >   uint256_t;

AFAIK Twoja metoda ma największy sens, z tym że używałbym też boostowego 128-bitowego inta.

2

Google podpowiada, że istnieje coś takiego jak boost::multiprecision::export_bits. Lecąc bit po bicie:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/iterator/function_output_iterator.hpp>
#include <string>
#include <iostream>

int main() {
    boost::multiprecision::uint256_t result = 534534;

    std::string s;
    boost::multiprecision::export_bits(
        result,
        boost::make_function_output_iterator(
            [&s](unsigned int d) { s.push_back(d ? '1': '0'); }
        ),
        1
    );
    std::cout << s << "\n";
}

Albo w chunkach po 8 bitów:

#include <boost/multiprecision/cpp_int.hpp>
#include <boost/iterator/function_output_iterator.hpp>
#include <string>
#include <iostream>
#include <bitset>

int main() {
    boost::multiprecision::uint256_t result = 534534;

    std::string s;
    boost::multiprecision::export_bits(
        result,
        boost::make_function_output_iterator(
            [&s](uint8_t d) { s += std::bitset<8>(d).to_string(); }
        ),
        8
    );
    std::cout << s << "\n";
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1