13 UNKNOWN_ENDIAN = 0x0000
16 #define UNKNOWN_ENDIAN (0x0000)
18 int get_host_endian();
19 int parse_endian(const char* arg);
20 const char* endian2str(int endian);
22 // change the byte order of given variable
23 template <typename Type>
24 Type change_byte_order(const Type& v){
26 const size_t size = sizeof(v);
27 uint8_t* first = (uint8_t *) (&t);
28 uint8_t* last = first + size - 1;
29 while (first < last) {
30 std::swap(*first++, *last--);
40 static TargetType create(const T& from){
46 #define DEFINE_OTHER_TYPE(__T__) typedef __T__ ## _BE TargetType
48 #define DEFINE_OTHER_TYPE(__T__) typedef __T__ ## _LE TargetType
52 // we always defined a reversed layout of big-endian and little-endian
53 // bit-field struct, so such kind of struct need to be reverted if host
54 // arch is different from build arch.
57 bool revert_write(const T& t, FILE *fp){
58 T reverted = change_byte_order(t);
59 typename OtherEndian<T>::TargetType o =
60 OtherEndian<T>::create(reverted);
61 return fwrite(&o, sizeof(o), 1, fp) == 1;
65 // if the struct has non-bit-field member(s), TTransUnit, among others,
66 // the order of members is the same as how they are defined.
72 Writer(FILE *fp, bool doRevert)
73 : m_fp(fp), m_doRevert(doRevert)
77 bool write(const T& t){
79 return revert_write(t, m_fp);
81 return fwrite(&t, sizeof(t), 1, m_fp) == 1;
86 bool write(const T* t, size_t len){
87 for (unsigned i = 0; i < len; i++) {
95 const bool m_doRevert;