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