Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

endianness influence in C++ code

I know that this might be a silly question, but I am a newbie C++ developer and I need some clarifications about the endianness.

I have to implement a communication interface that relies on SCTP protocol in order to communicate between two different machines (one ARM based, and the other Intel based).

The aim is to:

  1. encode messages into a stream of bytes to be sent on the socket (I used a vector of uint8_t, and positioned each byte of the different fields -taking care of splitting uint16/32/64 to single bytes- following big-endian convention)
  2. send the bytestream via socket to the receiver (using stcp)
  3. retrieve the stream and parse it in order to fill the message object with the correct elements (represented by header + TV information elements)

I am confused on where I could have problem with the endianness of the underlying architecture of the 2 machines in where the interface will be used. I think that taking care of splitting objects into single bytes and positioning them using big-endian can preclude that, at the arrival, the stream is represented differently, right? or am I missing something?

Also, I am in doubt about the role of C++ representation of multiple-byte 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);

This piece of code is endianness dependent or not? i.e. if I work on a big-endian machine I suppose that the above code is ok, but if it is little-endian, will I pick up the bytes in different order?

I've searched already for such questions but no one gave me a clear reply, so I have still doubts on this.

Thank you all in advance guys, have a nice day!

like image 515
panc_fab Avatar asked Jan 29 '23 16:01

panc_fab


1 Answers

This piece of code is endianness dependent or not?

No the code doesn't depend on endianess of the target machine. Bitwise operations work the same way as e.g. mathematical operators do.

They are independent of the internal representation of the numbers.


Though if you're exchanging data over the wire, you need to have a defined byte order known at both sides. Usually that's network byte ordering (i.e. big endian).

The functions of the htonx() ntohx() family will help you do en-/decode the (multibyte) numbers correctly and transparently.

like image 101
user0042 Avatar answered Feb 08 '23 16:02

user0042