summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn-Mark Bell <jmb@netsurf-browser.org>2018-01-20 15:05:58 +0000
committerJohn-Mark Bell <jmb@netsurf-browser.org>2018-01-20 15:05:58 +0000
commit192fe1466babdb48883dfd1d52acf68062589f9b (patch)
treec5bdcfa69c87f958f2340c4745947a35c06c6d65
parent00f66c004fc24e381151937d15f58ee30cabce7f (diff)
downloadlibnsutils-192fe1466babdb48883dfd1d52acf68062589f9b.tar.gz
libnsutils-192fe1466babdb48883dfd1d52acf68062589f9b.tar.bz2
Add endian.h
-rw-r--r--include/nsutils/endian.h68
1 files changed, 68 insertions, 0 deletions
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 <jmb@netsurf-browser.org>
+ */
+
+/**
+ * \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