The impact of endianness in C ++ - code

I know this might be a dumb question, but I'm a C ++ developer for beginners, and I need some clarification about the content.

I need to implement a communication interface that uses SCTP to communicate between two different computers (one ARM-based and the other based on Intel).

The goal is as follows:

  • encode messages into a byte stream that should be sent to the socket (I used the uint8_t vector and positioned each byte of different fields - taking care of dividing uint16 / 32/64 into single bytes - after the big-endian convention)
  • send byte stream over socket to receiver (using stcp)
  • it extracts the stream and analyzes it to fill the message object with the correct elements (represented by the elements of the + TV header).

I am confused about where I might have a problem with the content of the basic architecture of the two machines that will use the interface. I think that taking care of breaking objects into separate bytes and positioning them using big-endian may eliminate the possibility that the stream is presented differently upon arrival, right? or am I missing something?

In addition, I doubt the role of the C ++ representation for multibyte variables, for example:

uint16_t var=0x0123;

//low byte 0x23 
uint8_t low = (uint8_t)var;

//hi byte 0x01
uint8_t hi = (uint8_t)(var >> 8);

Does this piece of code depend on the goal or not? those. if I work on a large end machine, I believe that the above code is ok, but if it is of little importance, will I take the bytes in a different order?

I have already searched for such questions, but no one has given me a clear answer, so I still doubt it.

Thanks to everyone in advance guys, have a nice day!

+4
2

?

. , , , .

.


, , , . (.. ).

htonx() ntohx() () .

+6

, , .

, , :

// Don't do this!
uint16_t var=0x0123;
auto p = reinterpret_cast<char*>(&var);
uint8_t hi = p[0]; // 0x01 or 0x23 (probably!)
uint8_t lo = p[1]; // 0x23 or 0x01 (probably!)

( , , , , , , ++)

+2

Source: https://habr.com/ru/post/1684901/


All Articles