cpp_bin_float_import_export.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. ///////////////////////////////////////////////////////////////
  2. // Copyright 2015 John Maddock. Distributed under the Boost
  3. // Software License, Version 1.0. (See accompanying file
  4. // LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt
  5. #include <boost/multiprecision/cpp_bin_float.hpp>
  6. #include <iostream>
  7. #include <iomanip>
  8. #include <vector>
  9. #include <iterator>
  10. // Contains Quickbook snippets in comments.
  11. //[IE2
  12. /*`
  13. Importing or exporting cpp_bin_float is similar, but we must procede via an intermediate integer:
  14. */
  15. /*=
  16. #include <boost/multiprecision/cpp_bin_float.hpp>
  17. #include <iostream>
  18. #include <iomanip>
  19. #include <vector>
  20. #include <iterator>
  21. */
  22. int main()
  23. {
  24. using boost::multiprecision::cpp_bin_float_100;
  25. using boost::multiprecision::cpp_int;
  26. // Create a cpp_bin_float to import/export:
  27. cpp_bin_float_100 f(1);
  28. f /= 3;
  29. // export into 8-bit unsigned values, most significant bit first:
  30. std::vector<unsigned char> v;
  31. export_bits(cpp_int(f.backend().bits()), std::back_inserter(v), 8);
  32. // Grab the exponent as well:
  33. int e = f.backend().exponent();
  34. // Import back again, and check for equality, we have to procede via
  35. // an intermediate integer:
  36. cpp_int i;
  37. import_bits(i, v.begin(), v.end());
  38. cpp_bin_float_100 g(i);
  39. g.backend().exponent() = e;
  40. BOOST_ASSERT(f == g);
  41. }
  42. //]