How to achieve cross-platform serialization, working directly with bits, composing packages for sending between classes, provided that bit manipulations must be correct for little endian and big endian .
3 answers
When communicating within the same system, taking into account the order of bytes makes no sense. all threads, processes, etc. work with one order. The question arises only when transferring information to another platform. Those. data should be reduced to a predetermined byte order only when transmitting over a network or when writing to files that can later be transferred to another system.
In the fields of the structures used for the exchange, store the data in a network format (network order, you can find out more here ).
You can use the htons()/htonl()/ntohs()/ntohl() from the Berkeley sockets API to convert data between the network format and the host format.
- If big endian is called "network format" it will not become more popular. Most systems use little endian (x86), so why waste time converting to BE and back if both the client and the server are most likely LE? - Abyx
- @Abyx, probably out of habit. Once (back in the times when RPC and NFS were only sculpted) people implicitly (or, obviously, I don’t remember) already agreed on this (by the way, then big endian (VAX, pdp) was more common among developers) - avp
- oneStill confused. VAX and PDP were little-endian, and MC68xxx big-endian. In any case , it will take a lot of time for the Internet Protocol Standard (STD 2) to be big-endian - avp
- @Abyx, by the way, Java big-endian (and this is a bunch of progs on android), so the question of the prevalence of the format clearly remains open. - avp
Inside a byte, bits always go from left to right from the highest to the lowest, regardless of the received byte order in the system. The same applies to operands for operators >> << , even if they are numbers consisting of more than one byte. That is, int i=4; i>>=1; int i=4; i>>=1; i will always be 2.
For cross-platform (de) serialization, you can use htons () / htonl () / ntohs () / ntohl ()
>>and<<) and so cross-platform. - Abyx