Skip to content

Instantly share code, notes, and snippets.

@dallarosa
Created February 12, 2015 11:12
Show Gist options
  • Save dallarosa/412235a6101e5fda3bed to your computer and use it in GitHub Desktop.
Save dallarosa/412235a6101e5fda3bed to your computer and use it in GitHub Desktop.
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
char * int2bin(int i)
{
size_t bits = sizeof(int) * CHAR_BIT;
char * str = malloc(bits + 1);
if(!str) return NULL;
str[bits] = 0;
// type punning because signed shift is implementation-defined
unsigned u = *(unsigned *)&i;
for(; bits--; u >>= 1)
str[bits] = u & 1 ? '1' : '0';
return str;
}
int main() {
char a = (char)129;
printf("char: %c\n",a);
printf("octal: %o\n",a);
printf("hexa: %x\n",a);
printf("unsigned: %u\n",a);
printf("binary: %s\n",int2bin(a));
printf("char: %c\n",129);
printf("octal: %o\n",129);
printf("hexa: %x\n",129);
printf("unsigned: %u\n",129);
printf("binary: %s\n",int2bin(129));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment