diff options
author | Stefan Kerkmann <[email protected]> | 2024-10-12 18:48:00 +0200 |
---|---|---|
committer | GitHub <[email protected]> | 2024-10-12 18:48:00 +0200 |
commit | 5478051d7470efb32783b1c4080a2c3f24ce3c24 (patch) | |
tree | 81dfe3ba5b08ec29edf3156b109cff453be23c65 /quantum | |
parent | 6fa11bf21913b5ccb531acc3c2baec963f4d384a (diff) | |
download | qmk_firmware-5478051d7470efb32783b1c4080a2c3f24ce3c24.tar.gz qmk_firmware-5478051d7470efb32783b1c4080a2c3f24ce3c24.zip |
[Core] quantum: util: add bit and bitmask helpers (#24229)
quantum: util: add bit and bitmask helpers
These helpers are handy and can prevent off-by-one errors when working
with registers and general low level bit manipulation tasks. The macros
themself are inspired by the bits.h macros from the linux kernel source
code.
Signed-off-by: Stefan Kerkmann <[email protected]>
Co-authored-by: Pascal Getreuer <[email protected]>
Diffstat (limited to 'quantum')
-rw-r--r-- | quantum/bits.h | 33 | ||||
-rw-r--r-- | quantum/util.h | 1 |
2 files changed, 34 insertions, 0 deletions
diff --git a/quantum/bits.h b/quantum/bits.h new file mode 100644 index 0000000000..2f3c343762 --- /dev/null +++ b/quantum/bits.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +#pragma once + +#include <stdint.h> + +/* Remove these once we transitioned to C23 across all platfroms */ +#define UINT32_WIDTH 32 +#define UINT64_WIDTH 64 + +/** + * @brief Mask for the little endian nth bit (0-31) in a 32-bit integer. + */ +#define BIT32(n) (UINT32_C(1) << (n)) + +/** + * @brief Mask for the little endian nth bit (0-63) in a 64-bit integer. + */ +#define BIT64(n) (UINT64_C(1) << (n)) + +/** + * @brief Create a contiguous 32-bit wide bitmask starting at bit position @l + * and ending at position @h. The range is inclusive, meaning GENMASK32(20, 10) + * gives us the 32-bit mask 0x001ffc00. + */ +#define GENMASK32(h, l) (((~UINT32_C(0)) - (UINT32_C(1) << (l)) + 1) & (~UINT32_C(0) >> (UINT32_WIDTH - 1 - (h)))) + +/** + * @brief Create a contiguous 64-bit wide bitmask starting at bit position @l + * and ending at position @h. The range is inclusive, meaning GENMASK64(39, 21) + * gives us the 64-bit mask 0x000000ffffe00000. + */ +#define GENMASK64(h, l) (((~UINT64_C(0)) - (UINT64_C(1) << (l)) + 1) & (~UINT64_C(0) >> (UINT64_WIDTH - 1 - (h)))) diff --git a/quantum/util.h b/quantum/util.h index 94d9f22317..61ec7ac153 100644 --- a/quantum/util.h +++ b/quantum/util.h @@ -4,6 +4,7 @@ #pragma once +#include "bits.h" #include "bitwise.h" // convert to string |