90 lines
2.2 KiB
C
90 lines
2.2 KiB
C
#ifndef NETWORK_BYTE_ORDER_H
|
|
#define NETWORK_BYTE_ORDER_H
|
|
|
|
#include <stdint.h>
|
|
|
|
|
|
static inline uint64_t hton64(uint64_t host);
|
|
static inline uint32_t hton32(uint32_t host);
|
|
static inline uint16_t hton16(uint16_t host);
|
|
static inline uint8_t hton8 (uint8_t host);
|
|
|
|
#define hton(x) _Generic( (x), \
|
|
uint64_t : hton64, \
|
|
uint32_t : hton32, \
|
|
uint16_t : hton16, \
|
|
uint8_t : hton8 \
|
|
)(x)
|
|
|
|
[[gnu::alias("hton64")]] static inline uint64_t ntoh64(uint64_t network);
|
|
[[gnu::alias("hton32")]] static inline uint32_t ntoh32(uint32_t network);
|
|
[[gnu::alias("hton16")]] static inline uint16_t ntoh16(uint16_t network);
|
|
[[gnu::alias("hton8") ]] static inline uint8_t ntoh8 (uint8_t network);
|
|
|
|
#define ntoh(x) _Generic( (x), \
|
|
uint64_t : ntoh64, \
|
|
uint32_t : ntoh32, \
|
|
uint16_t : ntoh16, \
|
|
uint8_t : ntoh8 \
|
|
)(x)
|
|
|
|
#ifndef NETWORK_BYTE_ORDER_IMPLEMENTED
|
|
#define NETWORK_BYTE_ORDER_IMPLEMENTED
|
|
#include <stdbool.h>
|
|
|
|
#define bswap64(x) \
|
|
((((x) & 0xff00000000000000ull) >> 56) \
|
|
| (((x) & 0x00ff000000000000ull) >> 40) \
|
|
| (((x) & 0x0000ff0000000000ull) >> 24) \
|
|
| (((x) & 0x000000ff00000000ull) >> 8) \
|
|
| (((x) & 0x00000000ff000000ull) << 8) \
|
|
| (((x) & 0x0000000000ff0000ull) << 24) \
|
|
| (((x) & 0x000000000000ff00ull) << 40) \
|
|
| (((x) & 0x00000000000000ffull) << 56))
|
|
#define bswap32(x) \
|
|
((((x) & 0xff000000ul) >> 24) \
|
|
| (((x) & 0x00ff0000ul) >> 8) \
|
|
| (((x) & 0x0000ff00ul) << 8) \
|
|
| (((x) & 0x000000fful) << 24))
|
|
#define bswap16(x) \
|
|
((((x) & 0xff00u) >> 8) \
|
|
| (((x) & 0x00ffu) << 8))
|
|
|
|
static inline bool is_big_endian(void){
|
|
return ((const union { uint16_t full; struct{ uint8_t high; uint8_t low; } __attribute__((packed)); } __attribute__((packed))) { .full = 1 }).low == 1;
|
|
}
|
|
|
|
static inline uint64_t hton64(uint64_t host){
|
|
if(is_big_endian()){
|
|
return host;
|
|
}
|
|
else{
|
|
return bswap64(host);
|
|
}
|
|
}
|
|
|
|
static inline uint32_t hton32(uint32_t host){
|
|
if(is_big_endian()){
|
|
return host;
|
|
}
|
|
else{
|
|
return bswap32(host);
|
|
}
|
|
}
|
|
|
|
static inline uint16_t hton16(uint16_t host){
|
|
if(is_big_endian()){
|
|
return host;
|
|
}
|
|
else{
|
|
return bswap16(host);
|
|
}
|
|
}
|
|
|
|
static inline uint8_t hton8 (uint8_t host){
|
|
return host;
|
|
}
|
|
#endif
|
|
|
|
#endif
|