Skip to content

Instantly share code, notes, and snippets.

@radiofreejohn
Created July 23, 2011 06:04
Show Gist options
  • Save radiofreejohn/1101089 to your computer and use it in GitHub Desktop.
Save radiofreejohn/1101089 to your computer and use it in GitHub Desktop.
integer to binary string
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
char *itob(char *buffer, int x)
{
unsigned int z = INT_MAX + 1U;
char *buf = buffer;
do
{
if (z & x)
*buffer++ = '1';
else if (buf != buffer)
*buffer++ = '0';
} while (z = z >> 1);
if (x == 0) *buffer++ = '0';
*buffer = '\0';
return buf;
}
int main(int argc, char *argv[])
{
int x;
char buffer[43];
if (argc == 2)
{
x = atoi(argv[1]);
printf("%d to binary: %s \n", x, itob(buffer,x));
} else {
printf("enter a number.\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment