summaryrefslogtreecommitdiff
path: root/ucoo/utils
diff options
context:
space:
mode:
authorNicolas Schodet2015-06-08 15:02:30 +0200
committerNicolas Schodet2019-10-07 00:44:50 +0200
commitb17f8244eda5a3849d1af0a93744e345ae07d090 (patch)
treee4eed396255c1e3877df44064123b47bbf00af23 /ucoo/utils
parent41fde87ed8d1fcd593777bdfae2fa9e65006d984 (diff)
ucoo/utils: add bytes buffer pack/unpack
Diffstat (limited to 'ucoo/utils')
-rw-r--r--ucoo/utils/bytes.hh42
1 files changed, 42 insertions, 0 deletions
diff --git a/ucoo/utils/bytes.hh b/ucoo/utils/bytes.hh
index f922720..3fe7745 100644
--- a/ucoo/utils/bytes.hh
+++ b/ucoo/utils/bytes.hh
@@ -40,6 +40,27 @@ bytes_pack (uint8_t b3, uint8_t b2, uint8_t b1, uint8_t b0)
return b3 << 24 | b2 << 16 | b1 << 8 | b0;
}
+/// Pack a number of bytes to one word of any size, little endian.
+template<typename T>
+static inline T
+bytes_pack (const uint8_t *b)
+{
+ struct pack_struct
+ {
+ T value;
+ } __attribute__ ((packed));
+ return reinterpret_cast<const pack_struct *> (b)->value;
+}
+
+/// Pack a number of bytes to one word of any size, little endian, char
+/// version.
+template<typename T>
+static inline T
+bytes_pack (const char *b)
+{
+ return bytes_pack<T> (reinterpret_cast<const uint8_t *> (b));
+}
+
/// Unpack one byte from one 32 bit word.
static inline uint8_t
bytes_unpack (uint32_t w, int n)
@@ -47,6 +68,27 @@ bytes_unpack (uint32_t w, int n)
return (w >> (n * 8)) & 0xff;
}
+/// Unpack a word of any size to a number of bytes, little endian.
+template<typename T>
+static inline void
+bytes_unpack (uint8_t *b, T value)
+{
+ struct pack_struct
+ {
+ T value;
+ } __attribute__ ((packed, aligned(1)));
+ reinterpret_cast<pack_struct *> (b)->value = value;
+}
+
+/// Unpack a word of any size to a number of bytes, little endian, char
+/// version
+template<typename T>
+static inline void
+bytes_unpack (char *b, T value)
+{
+ bytes_unpack (reinterpret_cast<uint8_t *> (b), value);
+}
+
} // namespace ucoo
#endif // ucoo_utils_bytes_hh