Created
May 1, 2026 18:24
-
-
Save mancap314/572ecfe19b5ad0be4f230e4161235757 to your computer and use it in GitHub Desktop.
X Macro, for clz on 8-bits integer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Example of using X Macros for computing | |
| * ffs (find first set) a.k.a. clz (count leading zeros) | |
| * on 8-bits integer (uint8_t) | |
| * See https://mancap314.github.io/xmacros.html | |
| */ | |
| #include <stdint.h> | |
| #include <stdio.h> | |
| #define U8CLZ_LIST \ | |
| U8CLZ(1) U8CLZ(2) U8CLZ(3) U8CLZ(4) U8CLZ(5) U8CLZ(6) U8CLZ(7) | |
| /* function returning the first bit set in `u` | |
| * (u & -u) contains only one bit set to 1, at the | |
| * position of the fist bit set. So we switch (u & -u) | |
| * over 1 << 1 ... 1 << 7 to find the position of this bit. | |
| * Note: if u == 0 or (u & -u == 1) it returns 0. | |
| */ | |
| uint8_t u8clz(uint8_t u) { | |
| uint8_t ret = 0; | |
| switch (u & -u) { | |
| #define U8CLZ(u) \ | |
| case 1 << u: \ | |
| ret = u; \ | |
| break; | |
| U8CLZ_LIST | |
| #undef U8CLZ | |
| } | |
| return ret; | |
| } | |
| void test_u8clz(void) { | |
| #define FOR_TEST_VALUES(DO) DO(1) DO(40) DO(255) DO(18) DO(1 << 4) | |
| #define PRINT_VALUE_AND_CLZ(v) printf("u8clz(%u): %u\n", v, u8clz(v)); | |
| FOR_TEST_VALUES(PRINT_VALUE_AND_CLZ) | |
| } | |
| int main(void) { | |
| test_u8clz(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment