Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To understand a C code about endianness

Tags:

c

endianness

I am studying big and little-endianness.

1. What is the purpose of | \ in the following code?

...

#elif defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)

  #define htons(A) ((((uint16_t)(A) & 0xff00) >> 8) | \
                    (((uint16_t)(A) & 0x00ff) << 8))
...

2. What is the purpose of (A) in the code?

like image 320
Léo Léopold Hertz 준영 Avatar asked Feb 06 '26 04:02

Léo Léopold Hertz 준영


1 Answers

The '|' is the bitwise OR operator. It basically combines the values. The 'A' is the parameter from the #define htons. It is enclosed in parentheses so that expressions will not confuse the programmer or compiler. The '\' continues the macro onto the next line. (A macro usually ends at the end of the line.)

This macro takes the 16-bit value in A and masks out the top 8 bits. It then takes that value and shifts it right 8 bits. That means the top 8 bits are now on the bottom of the 16-bit value. It next masks out the top 8 bits of the original value in A and shifts those left 8 bits. That means the bottom 8 bits are now on the top. Finally, it recombines the two values back into one value.

The end result is that the top and bottom bytes have had their places swapped.

like image 55
Christopher Avatar answered Feb 09 '26 03:02

Christopher