From 19a46e0f9691e6acf0b6c400508397f1e1e05472 Mon Sep 17 00:00:00 2001 From: Dmitry Muhomor Date: Fri, 27 Oct 2023 21:14:32 +0300 Subject: [PATCH] add helper functions for using u8 array as u4 array --- util.h | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/util.h b/util.h index 9a4a7af..9b5abe6 100644 --- a/util.h +++ b/util.h @@ -1,6 +1,7 @@ #ifndef UTIL_H #define UTIL_H +#include #include #include #include @@ -57,6 +58,23 @@ static inline size_t align(size_t size, size_t align) { return (size + mask) & ~mask; } +// u4_arr_{set,get} are helper functions for using u8 array as an array of unsigned 4-bit values. +static_assert(sizeof(u8) == 1, "unexpected u8 size"); + +// val is treated as a 4-bit value +static inline void u4_arr_set(u8 *arr, size_t idx, u8 val) { + size_t off = idx >> 1; + size_t shift = (idx & 1) << 2; + u8 mask = (u8) (0xf0 >> shift); + arr[off] = (arr[off] & mask) | (val << shift); +} + +static inline u8 u4_arr_get(const u8 *arr, size_t idx) { + size_t off = idx >> 1; + size_t shift = (idx & 1) << 2; + return (u8) ((arr[off] >> shift) & 0xf); +} + COLD noreturn void fatal_error(const char *s); #if CONFIG_SEAL_METADATA