Last active
December 14, 2015 18:09
-
-
Save boredzo/5127750 to your computer and use it in GitHub Desktop.
Weird bit-printing behavior—run it and see what happens
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
| #import <Foundation/Foundation.h> | |
| static NSString *int32tostr(int value); | |
| int main(int argc, char *argv[]) { | |
| @autoreleasepool { | |
| NSLog(@"%@", int32tostr(1)); | |
| NSLog(@"%@", int32tostr(2)); | |
| NSLog(@"%@", int32tostr(3)); | |
| } | |
| } | |
| static NSString *int32tostr(int value) { | |
| unsigned int uval = (unsigned int)value; | |
| #if BIG_ENDIAN | |
| unsigned int bigvalue = uval; | |
| #elif LITTLE_ENDIAN | |
| unsigned int bigvalue = NSSwapHostIntToBig(uval); | |
| #endif | |
| enum { | |
| numBits = sizeof(value) * 8, | |
| numOutputChars = numBits + 1 | |
| }; | |
| char buf[numOutputChars]; | |
| signed int i = numBits; | |
| while (i > -1) { | |
| unsigned int j = numBits - i; | |
| buf[j] = '0' + ((bigvalue >> i) & 1); | |
| --i; | |
| } | |
| buf[numBits] = '\0'; | |
| NSString *str = [NSString stringWithUTF8String:buf]; | |
| return str; | |
| } |
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
| //Version that works | |
| #import <Foundation/Foundation.h> | |
| static const char *int32tostr(int value); | |
| int main(int argc, char *argv[]) { | |
| @autoreleasepool { | |
| for(int i = 0; i < 16; ++i) { | |
| printf("%s\n", int32tostr(i)); | |
| } | |
| } | |
| } | |
| static const char *int32tostr(int value) { | |
| unsigned int uval = (unsigned int)value; | |
| #if BIG_ENDIAN | |
| unsigned int bigvalue = uval; | |
| #elif LITTLE_ENDIAN | |
| unsigned int bigvalue = NSSwapHostIntToBig(uval); | |
| #endif | |
| enum { | |
| numBits = sizeof(value) * 8, | |
| numOutputChars = numBits + 1 | |
| }; | |
| static char buf[numOutputChars]; | |
| signed int i = numBits; | |
| while (i > -1) { | |
| buf[numBits - (i + 1)] = '0' + ((bigvalue >> i) & 1); | |
| --i; | |
| } | |
| buf[numBits] = '\0'; | |
| return buf; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment