Created
February 12, 2015 11:12
-
-
Save dallarosa/412235a6101e5fda3bed to your computer and use it in GitHub Desktop.
Code for question http://stackoverflow.com/questions/28404460/casting-of-char-in-ruby-is-different-in-c
This file contains hidden or 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> | |
#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