Skip to content

Instantly share code, notes, and snippets.

@cota
Created September 7, 2011 05:36
Show Gist options
  • Save cota/1199847 to your computer and use it in GitHub Desktop.
Save cota/1199847 to your computer and use it in GitHub Desktop.
simple macros to extract u{8,16,32}'s from variables.
/*
* bitslice.c
* build with gcc -Wall.
*
* simple macros to extract u{8,16,32}'s from variables.
*/
#include <stdint.h>
#include <stdio.h>
#define __shift(n, log) ((n) << (log))
#define logmask(log) ((1ULL << (1 << (log))) - 1)
#define __get_slice(x, n, log) \
(((x) >> __shift((n), (log))) & logmask(log))
#define get_u8(x, n) __get_slice((x), (n), 3)
#define get_u16(x, n) __get_slice((x), (n), 4)
#define get_u32(x, n) __get_slice((x), (n), 5)
int main(int argc, char *argv[])
{
unsigned long long val = 0xcafebabedeadbeef;
uint8_t getu8[8];
uint16_t getu16[8];
uint32_t getu32[8];
int i, j;
printf("u64\t%llx\n", val);
printf("u32\t");
for (i = 0; i < sizeof(val) / sizeof(getu32[0]); i++) {
j = 7 - i;
getu32[i] = get_u32(val, j);
printf("%x ", getu32[i]);
}
printf("\n");
printf("u16\t");
for (i = 0; i < sizeof(val) / sizeof(getu16[0]); i++) {
j = 7 - i;
getu16[i] = get_u16(val, j);
printf("%x ", getu16[i]);
}
printf("\n");
printf("u8\t");
for (i = 0; i < sizeof(val) / sizeof(getu8[0]); i++) {
j = 7 - i;
getu8[i] = get_u8(val, j);
printf("%x ", getu8[i]);
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment