Skip to content

Instantly share code, notes, and snippets.

@benwills
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benwills/fc7956988be1a47e0449 to your computer and use it in GitHub Desktop.
Save benwills/fc7956988be1a47e0449 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
unsigned
input = 0b0111u,
n_bits = 4u,
*bits = (unsigned*)malloc(sizeof(unsigned) * n_bits),
bit = 0;
for(bit = 0; bit < n_bits; ++bit)
bits[bit] = (input >> bit) & 1;
// Assuming that you want to calculate all bits as in this case, and
// not a specific one, the loop can be further changed to
for(bit = 0; bit < n_bits; ++bit, input >>= 1)
bits[bit] = input & 1;
// This modifies input in place and thereby allows the use of a
// constant width, single-bit shift, which may be more efficient on
// some architectures.
for(bit = n_bits; bit--;)
printf("%u", bits[bit]);
printf("\n");
free(bits);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment