Skip to content

Instantly share code, notes, and snippets.

@jacksonfdam
Created May 25, 2012 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacksonfdam/2790642 to your computer and use it in GitHub Desktop.
Save jacksonfdam/2790642 to your computer and use it in GitHub Desktop.
Convert Signed Or Unsigned Integers To Binary In NSString
- (NSString *)intToBinary:(int)number
{
// Number of bits
int bits = sizeof(number) * 8;
// Create mutable string to hold binary result
NSMutableString *binaryStr = [NSMutableString string];
// For each bit, determine if 1 or 0
// Bitwise shift right to process next number
for (; bits > 0; bits--, number >>= 1)
{
// Use bitwise AND with 1 to get rightmost bit
// Insert 0 or 1 at front of the string
[binaryStr insertString:((number & 1) ? @"1" : @"0") atIndex:0];
}
return (NSString *)binaryStr;
}
Here is a range of examples:
NSLog(@"Int: %d", 0);
NSLog(@"Binary: %@", [self intToBinary:0]);
NSLog(@"Int: %d", 123);
NSLog(@"Binary: %@", [self intToBinary:123]);
NSLog(@"Int: %d", -123);
NSLog(@"Binary: %@", [self intToBinary:-123]);
NSLog(@"Int: %d", 999999);
NSLog(@"Binary: %@", [self intToBinary:999999]);
NSLog(@"Int: %d", -999999);
NSLog(@"Binary: %@", [self intToBinary:-999999]);
NSLog(@"Int: %d", 2147483647);
NSLog(@"Binary: %@", [self intToBinary:2147483647]);
And the corresponding output:
Int: 0
Binary: 00000000000000000000000000000000
Int: 123
Binary: 00000000000000000000000001111011
Int: -123
Binary: 11111111111111111111111110000101
Int: 999999
Binary: 00000000000011110100001000111111
Int: -999999
Binary: 11111111111100001011110111000001
Int: 2147483647
Binary: 01111111111111111111111111111111
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment