From 192fe1466babdb48883dfd1d52acf68062589f9b Mon Sep 17 00:00:00 2001 From: John-Mark Bell Date: Sat, 20 Jan 2018 15:05:58 +0000 Subject: Add endian.h --- include/nsutils/endian.h | 68 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 include/nsutils/endian.h diff --git a/include/nsutils/endian.h b/include/nsutils/endian.h new file mode 100644 index 0000000..4fe2420 --- /dev/null +++ b/include/nsutils/endian.h @@ -0,0 +1,68 @@ +/* + * This file is part of LibNSUtils. + * Licensed under the MIT License, + * http://www.opensource.org/licenses/mit-license.php + * Copyright 2009 John-Mark Bell + */ + +/** + * \file + * Endianness helper functions. + */ + +#ifndef NSUTILS_ENDIAN_H_ +#define NSUTILS_ENDIAN_H__ + +/** + * Detect if the host is little endian. + * + * \return True if the host is little endian; false otherwise. + */ +static inline bool endian_host_is_le(void) +{ + static uint32_t magic = 0x10000002; + + return (((uint8_t *) &magic)[0] == 0x02); +} + +/** + * Swap the endianness of a 32bit value. + * + * \param val Value to swap endianness of + * \return Endian-swapped value + */ +static inline uint32_t endian_swap(uint32_t val) +{ + return ((val & 0xff000000) >> 24) | ((val & 0x00ff0000) >> 8) | + ((val & 0x0000ff00) << 8) | ((val & 0x000000ff) << 24); +} + +/** + * Convert a host-endian 32bit value to its big-endian equivalent. + * + * \param host Value to convert + * \return Big endian value + */ +static inline uint32_t endian_host_to_big(uint32_t host) +{ + if (endian_host_is_le()) + return endian_swap(host); + + return host; +} + +/** + * Convert a big-endian 32bit value to its host-endian equivalent. + * + * \param host Value to convert + * \return Host endian value + */ +static inline uint32_t endian_big_to_host(uint32_t big) +{ + if (endian_host_is_le()) + return endian_swap(big); + + return big; +} + +#endif -- cgit v1.2.3