Skip to content

Instantly share code, notes, and snippets.

@boredzo
Last active December 14, 2015 18:09
Show Gist options
  • Select an option

  • Save boredzo/5127750 to your computer and use it in GitHub Desktop.

Select an option

Save boredzo/5127750 to your computer and use it in GitHub Desktop.
Weird bit-printing behavior—run it and see what happens
#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;
}
//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