Answer the question
In order to leave comments, you need to log in
Little endian to Big endian conversion in C++, is it necessary for binary serialization?
Actually, there is a cross-platform code. The task is to implement binary data saving, the data will then be read not only from c ++.
As I understand it, in Windows Little Endian. But there are platforms where we have Big Endian.
What I want is to write code that is guaranteed to be in network byte order (Big Endian).
What I came up with so far:
Some macro, for example, from here: stackoverflow.com/questions/2100331/c-macro-defini...
then the function will look like this:
void saveInt(int a)
{
#ifdef BIG_ENDIAN
save(a);
#else // little endian
int b = htonl(a);
save(b);
#endif
}
Answer the question
In order to leave comments, you need to log in
In posix systems (I can’t check in Windows, but most likely it should be the same somewhere) there is a family of functions for working with big endian and little endian .
Regarding your question, I would do something like this
unsigned short store(unsigned short s) { return htobe16(s); }
unsigned int store(unsigned int s) { return htobe32(s); }
unsinged long store(unsigned long s) { if (sizeof(unsinged long) == 8) return htobe64(s); else return htobe32(s);}
unsigned short restore(unsinged short s) { return be16toh(s); }
// и т.д.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question