T
T
Trrrrr2014-05-12 10:25:24
C++ / C#
Trrrrr, 2014-05-12 10:25:24

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
}

Maybe you can somehow implement this more fun, otherwise you can write such a function for each data type.
Well, did I understand correctly that htons always flips bytes? If not, then it turns out that such code is not needed, just always call it, and inside it is something like the code that I wrote.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xandox, 2014-05-12
@Trrrrr

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); }
// и т.д.

Well, as you can see, you will have to solve the issue with unsinged long. it, depending on the bit depth of the system, has a different size.
PS. In fact, big endian is now only found on embedded systems and game consoles, and generally speaking, it does not depend on the OS, but on the processor. On x86 and amd64 always little endian. By this, think about it - do you need it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question