Convert Signed Or Unsigned Integers To Binary In NSString

The code below shows how to convert an integer, either signed or unsigned, into a binary value that is stored in an NSString object.

The trick is get the number of bits (sizeof times 8 bits per byte), and for each bit, determine if it is a 1 or 0.

Notice the number passed into the method intToBinary under goes a binary shift each time through the loop (line number 11). The rightmost bit is AND’ed with 1 and based on the result, either a 1 or 0 is prepended into a mutable string object. I’ve kept the code tight in the for loop, with no additional variables declared and one line of code in the loop itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (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

Comments are closed.