-1

I saw a question on stack overflow how to convert from one endian to another. And the solution was like this:

template <typename T>
void swap_endian(T& pX)
{
    char& raw = reinterpret_cast<char&>(pX);
    std::reverse(&raw, &raw + sizeof(T));
}

My question is. Will this solution swap the bits correctly? It will swaps the bytes in the correct order but it will not swap the bits.

Merni
  • 2,842
  • 5
  • 36
  • 42

4 Answers4

4

Yes it will, because there is no need to swap the bits.

Edit: Endianness has effect on the order in which the bytes are written for values of 2 bytes or more. Little endian means the least significant byte comes first, big-endian the other way around.

If you receive a big-eindian stream of bytes written by a little endian system, there is no debate what the most significant bit is within the bytes. If the bit order was affected you could not read each others byte streams reliably (even if it was just plain 8 bit ascii).

This can not be autmatically determined for 2-byte or bigger values, as the file system (or network layer) does not know if you send data a byte at a time, or if you are sending ints that are (e.g.) 4 bytes long.

If you have a direct 1-bit serial connection with another system, you will have to agree on little or big endian bit ordering at the transport layer.

2

bigendian vs little endian concerns itself with how bytes are ordered within a larger unit, such as an int,long, etc. The ordering of bits within a byte is the same.

nos
  • 223,662
  • 58
  • 417
  • 506
1

"Endianness" generally refers to byte order, not the order of the bits within those bytes. In this case, you don't have to reverse the bits.

Etienne de Martel
  • 34,692
  • 8
  • 91
  • 111
  • 1
    "Endianness" in the broad sense of the term can actually mean bit order, although it is more commonly associated with bytes. – kgriffs Jan 20 '11 at 21:03
1

You are correct, that function would only swap the byte order, not individual bits. This is usually sufficient for networking. Depending on your needs, you may also find the htons() family of functions useful.

From Wikipedia:

Most modern computer processors agree on bit ordering "inside" individual bytes (this was not always the case). This means that any single-byte value will be read the same on almost any computer one may send it to."

kgriffs
  • 4,080
  • 5
  • 37
  • 42