udt_conversion_example.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // udt_conversion_example.cpp --------------------------------------------------------//
  2. // Copyright Beman Dawes 2013
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // http://www.boost.org/LICENSE_1_0.txt
  5. //--------------------------------------------------------------------------------------//
  6. #include <boost/endian/detail/disable_warnings.hpp>
  7. #include <boost/endian/conversion.hpp>
  8. #include <iostream>
  9. #include <cstring>
  10. using namespace boost::endian;
  11. using std::cout;
  12. using std::endl;
  13. using boost::int32_t;
  14. using boost::int64_t;
  15. namespace user
  16. {
  17. class UDT
  18. {
  19. public:
  20. UDT() : id_(0), value_(0) {desc_[0] = '\0';}
  21. UDT(int32_t id, int64_t value, const char* desc) : id_(id), value_(value)
  22. {
  23. std::strncpy(desc_, desc, sizeof(desc_)-1);
  24. desc_[sizeof(desc_)-1] = '\0';
  25. }
  26. int32_t id() const {return id_;}
  27. int64_t value() const {return value_;}
  28. const char* desc() const {return desc_;}
  29. void id(int32_t x) {id_ = x;}
  30. void value(int64_t v) {value_ = v;}
  31. void desc(const char* s)
  32. {
  33. std::strncpy(desc_, s, sizeof(desc_)-1);
  34. desc_[sizeof(desc_-1)] = '\0';
  35. }
  36. friend void endian_reverse_inplace(UDT&);
  37. private:
  38. int32_t id_;
  39. int64_t value_;
  40. char desc_[56]; // '/0'
  41. };
  42. void endian_reverse_inplace(UDT& x)
  43. {
  44. boost::endian::endian_reverse_inplace(x.id_);
  45. boost::endian::endian_reverse_inplace(x.value_);
  46. }
  47. }
  48. int main(int, char* [])
  49. {
  50. user::UDT x(1, 123456789012345LL, "Bingo!");
  51. //cout << std::hex;
  52. cout << "(1) " << x.id() << ' ' << x.value() << ' ' << x.desc() << endl;
  53. user::endian_reverse_inplace(x);
  54. cout << "(2) " << x.id() << ' ' << x.value() << ' ' << x.desc() << endl;
  55. endian_reverse_inplace(x);
  56. cout << "(3) " << x.id() << ' ' << x.value() << ' ' << x.desc() << endl;
  57. conditional_reverse_inplace<order::little, order::big>(x);
  58. cout << "(4) " << x.id() << ' ' << x.value() << ' ' << x.desc() << endl;
  59. conditional_reverse_inplace(x, order::big, order::little);
  60. cout << "(5) " << x.id() << ' ' << x.value() << ' ' << x.desc() << endl;
  61. }
  62. #include <boost/endian/detail/disable_warnings_pop.hpp>