Convert string to __uint128_t using stringstreams

2019-05-16 09:03发布

问题:

I'm trying to extract different types of data from a string.

void                    readHeader(char buf[BUFFSIZE])
{
  std::istringstream    hdr(buf);
  __uint128_t           id_client;

  hdr >> id_client; // doesn't compile
}

I'm getting this error when I do that hdr >> id_client :

Unix/UnixSocket.cpp:158:10: error: ambiguous overload for ‘operator>>’ in ‘hdr >> id_client’ Unix/UnixSocket.cpp:158:10: note: candidates are: In file included from /usr/include/c++/4.7/sstream:39:0,
                 from Unix/UnixSocket.cpp:11: /usr/include/c++/4.7/istream:118:7: note: std::basic_istream<_CharT,
_Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__istream_type& (*)(std::basic_istream<_CharT, _Traits>::__istream_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT,
_Traits>::__istream_type = std::basic_istream<char>] <near match> /usr/include/c++/4.7/istream:118:7: note:   no known conversion for argument 1 from ‘__int128 unsigned’ to ‘std::basic_istream<char>::__istream_type& (*)(std::basic_istream<char>::__istream_type&) {aka std::basic_istream<char>& (*)(std::basic_istream<char>&)}’ /usr/include/c++/4.7/istream:122:7: note: std::basic_istream<_CharT,
_Traits>::__istream_type& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>::__ios_type& (*)(std::basic_istream<_CharT, _Traits>::__ios_type&)) [with _CharT = char; _Traits = std::char_traits<char>; std::basic_istream<_CharT,
_Traits>::__istream_type = std::basic_istream<char>; std::basic_istream<_CharT, _Traits>::__ios_type = std::basic_ios<char>] <near match> /usr/include/c++/4.7/istream:122:7:

Is there any way to properly store my id_client in this __uint128_t variable ?

回答1:

https://gmplib.org/ might help. The mpz_class class of the gmpxx object abstraction supports I/O operators and the mpz_export(...) function allows you to transform the result into an array of bytes. If they exceed 16 bytes you may throw an exception or complain otherwise. Not very fast but I guess fast to implement.