diff options
author | phk <phk@FreeBSD.org> | 2003-04-03 08:58:04 +0000 |
---|---|---|
committer | phk <phk@FreeBSD.org> | 2003-04-03 08:58:04 +0000 |
commit | 50ba1a096a67828c127b6a6a679b40f3bc7267f8 (patch) | |
tree | 3c58b25e2dee1f0937c6cbca9ace8dc5167c1cdf /sys | |
parent | a7c38434d26b2ac4e10d8be611cde12089261fe8 (diff) | |
download | FreeBSD-src-50ba1a096a67828c127b6a6a679b40f3bc7267f8.zip FreeBSD-src-50ba1a096a67828c127b6a6a679b40f3bc7267f8.tar.gz |
Add inline functions {be,le}{16,32,64}{enc,dec}() for encoding decoding
into byte strings of unknown alignment.
Diffstat (limited to 'sys')
-rw-r--r-- | sys/sys/endian.h | 108 |
1 files changed, 108 insertions, 0 deletions
diff --git a/sys/sys/endian.h b/sys/sys/endian.h index 027b59d..0458ffd 100644 --- a/sys/sys/endian.h +++ b/sys/sys/endian.h @@ -89,4 +89,112 @@ typedef __uint64_t uint64_t; #define le64toh(x) bswap64((x)) #endif /* _BYTE_ORDER == _LITTLE_ENDIAN */ +/* Alignment-agnostic encode/decode bytestream to/from little/big endian. */ + +static __inline uint16_t +be16dec(const void *pp) +{ + u_char const *p = pp; + + return ((p[0] << 8) | p[1]); +} + +static __inline uint32_t +be32dec(const void *pp) +{ + u_char const *p = pp; + + return ((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3]); +} + +static __inline uint64_t +be64dec(const void *pp) +{ + u_char const *p = pp; + + return (((uint64_t)be32dec(p) << 32) | be32dec(p + 4)); +} + +static __inline uint16_t +le16dec(const void *pp) +{ + u_char const *p = pp; + + return ((p[1] << 8) | p[0]); +} + +static __inline uint32_t +le32dec(const void *pp) +{ + u_char const *p = pp; + + return ((p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]); +} + +static __inline uint64_t +le64dec(const void *pp) +{ + u_char const *p = pp; + + return (((uint64_t)be32dec(p + 4) << 32) | be32dec(p)); +} + +static __inline void +be16enc(void *pp, uint16_t u) +{ + u_char *p = pp; + + p[0] = (u >> 8) & 0xff; + p[1] = u & 0xff; +} + +static __inline void +be32enc(void *pp, uint32_t u) +{ + u_char *p = pp; + + p[0] = (u >> 24) & 0xff; + p[1] = (u >> 16) & 0xff; + p[2] = (u >> 8) & 0xff; + p[3] = u & 0xff; +} + +static __inline void +be64enc(void *pp, uint64_t u) +{ + u_char *p = pp; + + be32enc(p, u >> 32); + be32enc(p + 4, u & 0xffffffff); +} + +static __inline void +le16enc(void *pp, uint16_t u) +{ + u_char *p = pp; + + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; +} + +static __inline void +le32enc(void *pp, uint32_t u) +{ + u_char *p = pp; + + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; + p[2] = (u >> 16) & 0xff; + p[3] = (u >> 24) & 0xff; +} + +static __inline void +le64enc(void *pp, uint64_t u) +{ + u_char *p = pp; + + be32enc(p, u & 0xffffffff); + be32enc(p + 4, u >> 32); +} + #endif /* _SYS_ENDIAN_H_ */ |