开发者

byte representation of numbers

I use the next way to get the byte representation of numbers in C++:

开发者_StackOverflow社区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:

  1. 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.

  2. 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.


Not true way. This way is not portable and often may result in undefined behavior. Because,

  1. Padding (done by compiler) is ignored
  2. 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


This will work. Just be sure that anything with virtual functions, pointers and so on won't be accurate next time you deserialize them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜