Skip to content

Instantly share code, notes, and snippets.

@boki1
Created November 1, 2023 00:06
Show Gist options
  • Save boki1/d0eb3dd60250da170310ab3863cc4ec0 to your computer and use it in GitHub Desktop.
Save boki1/d0eb3dd60250da170310ab3863cc4ec0 to your computer and use it in GitHub Desktop.
Convert a number from base power of 2 to decimal.
#include <stddef.h>
#include <stdio.h>
/* Base power of 2 to decimal */
static unsigned bpt2dec(unsigned x, size_t mask) {
int indec = 0;
const int bits = __builtin_popcount(mask);
for (int i = 0; x != 0; ++i, x >>= bits)
indec += ((x & mask) << (i * bits));
return indec;
}
static inline unsigned hex2dec(unsigned x) {
return bpt2dec(x, 0xf);
}
static inline unsigned oct2dec(unsigned x) {
return bpt2dec(x, 07);
}
static inline unsigned bin2dec(unsigned x) {
return bpt2dec(x, 0b1);
}
int main()
{
printf("hex2dec(0xffff) = %lu\n", hex2dec(0xffff));
printf("oct2dec(077) = %lu\n", oct2dec(077));
printf("bin2dec(0b1010) = %lu\n", bin2dec(0b1010));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment