byte order in a union and endianness

So do I get it right, that on different platforms
the outputed chars can swap depending on system
endianness?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

union meta
{
 unsigned short i;
 unsigned char ch[2];
};

int
main()
{
 meta m;
 m.i = 0xFFEF;

 cout
  << hex
  << "meta.short == "
  << m.i
  << ","
  << endl
  << "meta.char[0] == "
  << static_cast<unsigned short>(m.ch[0])
  << ",\n"
  << "meta.char[1] == "
  << static_cast<unsigned short>(m.ch[1])
  << "."
  << endl;

 return 0;
}


I have this output on a PC:
meta.short == ffef,
meta.char[0] == ef,
meta.char[1] == ff.


I merely guess, on an old PowerPC it would
[1] <=> [0] to show us big endian...
That's right.
Hey Karlis.. I am not able to understand this


1
2
3
meta m;
 m.i = 0xFFEF;


The value is assigned only for but you are printing out m.ch[0]. How is this possible??! Can you explain please
@karthick88: You need to read up on unions.
Well, for those reading this, but not much interested in unions: the size of union is as of it's largest data member, but all data members actually point to the same physical data each in its own way.
Topic archived. No new replies allowed.