Last active
August 29, 2015 14:13
-
-
Save benwills/fc7956988be1a47e0449 to your computer and use it in GitHub Desktop.
From http://stackoverflow.com/questions/2249731/how-to-get-bit-by-bit-data-from-a-integer-value-in-c
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
#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