Created
April 7, 2024 21:28
-
-
Save imaami/923bcf3c721bd307fe1bee8c4d3ef37c to your computer and use it in GitHub Desktop.
Print bits with x86_64 intrinsics
This file contains 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
/* Compile with "gcc -std=c23 -mbmi2 -mlzcnt" (gcc-14) | |
* or "gcc -std=c2x -mbmi2 -mlzcnt" (gcc-13) | |
*/ | |
#include <errno.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <immintrin.h> | |
static void | |
bitpr (uint64_t n) | |
{ | |
uint64_t b[9] = {'0'}; | |
unsigned z = (typeof(z))__builtin_ia32_lzcnt_u64(n); | |
for (typeof(z) i = (71U - z) >> 3U; i--;) { | |
b[i] = __builtin_bswap64(UINT64_C(3472328296227680304) | |
| (uint64_t)_pdep_u64(n, 72340172838076673ULL)); | |
if (!(n >>= 8U)) | |
break; | |
} | |
puts(&((char const *)&b[0])[z & 7U]); | |
} | |
int | |
main (int c, | |
char **v) | |
{ | |
for (int i = 0; ++i < c;) { | |
char *p = v[i]; | |
if (!*p) | |
continue; | |
errno = 0; | |
uint64_t n = _Generic(n, | |
typeof(1UL): strtoul, | |
typeof(1ULL): strtoull)(p, &p, 0); | |
if (errno || *p) | |
continue; | |
bitpr(n); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment