Skip to content

Instantly share code, notes, and snippets.

@mrnugget
Created September 8, 2014 15:36
Show Gist options
  • Select an option

  • Save mrnugget/65f17df2165e82aa483e to your computer and use it in GitHub Desktop.

Select an option

Save mrnugget/65f17df2165e82aa483e to your computer and use it in GitHub Desktop.
Copies the binary representation of an integer to a string
#include <string.h>
#include <stdio.h>
#define INT_BITS_NUM (8 * sizeof(int))
void intncpy(int src, char *dest, int len)
{
int bit = INT_BITS_NUM - 1;
int pos, is_set;
for (pos = 0; pos < len; pos++) {
is_set = src & (1 << bit);
if (is_set) {
dest[pos] = '1';
} else {
dest[pos] = '0';
}
bit--;
}
}
int main(int argc, char *argv[])
{
char a[INT_BITS_NUM + 1];
int i;
for (i = 0; i <= 31; i++) {
intncpy(1 << i, a, INT_BITS_NUM);
a[INT_BITS_NUM] = '\0';
printf("%s\n", a);
memset(a, '\0', INT_BITS_NUM);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment