I use the next way to get the byte representation of numbers in C++:
template< class T > union u_value { T value; unsigned char bytes[ sizeof( T ) ]; } Please, tell me is that the true way? And if not why and how should I get it?
There is no "true" way. What you did is one way to do it. Generally speaking, stuff like this is discouraged as it usually results in non-portable code. Sometimes there are good reasons for poking internals like that, but since you didn't tell what you're about to do with the "byte representation", there's little we can do to judge if this approach is appropriate.
Edit: So networking is your subject here. In this case, either:
You are transferring POD types only (char, short, int, the likes). In this case, you might want to look into <netinet/in.h>, where you'll find the macros htons(), htonl(), ntohs() and ntohl(), which do host-to-network-byte-order and vice versa for you.
You are transferring complex types (e.g. classes). In this case, you might want to look into Boost Serialization, because there's much more to be considered here than mere byte order.
Either way, it is advisable to use ready-made, well-documented and -understood code, instead of doing byte-juggling yourself.
0x0, 0x42 may be 0x0042 on one side and 0x4200 on the other. That's why we call this non-portable.int ?) and there's also the question how you encode floating-point types. Could be more I'm overlooking.Not true way. This way is not portable and often may result in undefined behavior. Because,
virtual function extra space is not taken care visibly (if T is polymorphic)If you are transferring the bytes across the network you need to be careful about the Endianess