Last active
July 20, 2022 16:34
-
-
Save opsJson/2a8f6e79ebd61f1e920ace01095be8d1 to your computer and use it in GitHub Desktop.
Easy way to set each individual bit of data of any size.
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
#include <stdio.h> | |
#include <stdarg.h> | |
unsigned int counter(const char *str) { | |
unsigned int i = 1; | |
while (*str) { | |
if (*str == ',') i++; | |
str++; | |
} | |
return i; | |
} | |
void BIT(void *dest, unsigned int count, ...) { | |
va_list args; | |
char bit, *ptr; | |
unsigned int i, j; | |
ptr = (char*)dest; | |
ptr[0] = 0; | |
va_start(args, count); | |
for (i=0,j=0; i<count; i++) { | |
bit = !!va_arg(args, int); | |
ptr[j] |= bit << (7 - (i % 8)); | |
if ((i+1) % 8 == 0) ptr[++j] = 0; | |
} | |
} | |
#define BIT(x, ...) BIT(x, counter(#__VA_ARGS__), __VA_ARGS__) | |
/*/////////////////////////////////// | |
Testing: | |
///////////////////////////////////*/ | |
int main(void) { | |
unsigned int c; | |
BIT(&c, 0, 0, 0, 0, 0, 0, 1, 0, | |
0, 0, 0, 0, 0, 0, 0, 1); | |
printf("%i\n", c); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment