Last active
January 24, 2022 11:55
-
-
Save UplinkCoder/4d355da7a77a28d666fe0708eef4486a to your computer and use it in GitHub Desktop.
header-only endian conversion macros
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef __ENDIAN_H_ | |
| #define __ENDIAN_H_ | |
| #include <stdint.h> | |
| #define NTOHL HTONL | |
| #define NTOHS HTONS | |
| #if !defined(ENDIAN_IS_LITTLE) && !defined(ENDIAN_IS_BIG) | |
| # if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && defined(__ORDER_BIG_ENDIAN__) | |
| # if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ | |
| # define ENDIAN_IS_LITTLE | |
| # elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ | |
| # define ENDIAN_IS_BIG | |
| # else | |
| # error "endian.h support little or big endian only." | |
| # endif | |
| # elif defined(_WIN32) | |
| # #define ENDIAN_IS_LITTLE | |
| # endif | |
| #endif | |
| #ifdef ENDIAN_IS_LITTLE | |
| #define HTONS(VAL) \ | |
| ((((VAL) & 0xff) << 8) \ | |
| | (((VAL) >> 8) & 0xff)) | |
| #define HTONL(VAL) \ | |
| ((((VAL) & 0xff) << 24) \ | |
| | (((VAL) >> 24) & 0xff) \ | |
| | (((VAL) & 0xff00) << 8) \ | |
| | (((VAL) >> 8) & 0xff00)) | |
| #elif ENDIAN_IS_BIG | |
| #define HTONS(VAL) \ | |
| (VAL) | |
| #define HTONL(VAL) \ | |
| (VAL) | |
| #else | |
| # error("Cannot determine endianness"); | |
| #endif | |
| #endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment