What is the correct approach in the Linux kernel to get the least or most significant byte of a 16 bit integer. Since the kernel can be compiled for little endian or big endian systems I can't just bit shift to get the value. I'm assuming there is a system dependant macro defined somewhere for use in the kernel code but I'm not sure what that would be.
Asked
Active
Viewed 306 times
1
-
Does this answer your question? [C Macro definition to determine big endian or little endian machine?](https://stackoverflow.com/questions/2100331/c-macro-definition-to-determine-big-endian-or-little-endian-machine) – Martheen Oct 21 '21 at 03:50
-
3It's the reverse: bitwise operations always give the correct mathematical answer regardless of endianness. `x & 0xff` always gives the least significant byte. Endianness only determines whether that byte is stored at a lower or a higher address. Likewise `(x >> 8) & 0xff` always gives the most significant byte. – Nate Eldredge Oct 21 '21 at 04:16
-
There are a bunch of macros/functions in "include/linux/byteorder/generic.h" for converting host (CPU) values to little- or big-endian byte order, and vice versa. For example, `cpu_to_le16(val)` converts a 16-bit, unsigned value from CPU byte order to little-endian byte order, and `le16_to_cpu(val)` converts a 16-bit, unsigned value from little-endian byte order to CPU byte order (`cpu_to_le16(val)` and `le16_to_cpu(val)` actually do the same thing, but are different functions for semantic checking of kernel sources by [Sparse](https://www.kernel.org/doc/html/latest/dev-tools/sparse.html).) – Ian Abbott Oct 21 '21 at 12:27
-
Note: do not include "include/linux/byteorder/generic.h" directly. Use `#include
`. – Ian Abbott Oct 21 '21 at 12:34 -
There are some other macros defined by `#include
`. `__BIG_ENDIAN` is defined (as `4321`) for big-endian architectures. `__LITTLE_ENDIAN` is defined (as `1234`) for little-endian architectures. Also, `__BIG_ENDIAN_BITFIELD` is defined if struct bitfield members are allocated from the most significant bit of the underlying storage unit downwards, and `__LITTLE_ENDIAN_BITFIELD` is defined if they are allocated from the least significant bit upwards. – Ian Abbott Oct 21 '21 at 12:44