views:

4088

answers:

2

I am trying to figure out how to convert an NSInteger, say 56, to an NSString that is a binary representation of the original (int) value. Perhaps someone knows a formatting technique that can accept 56 and return "111000" within Objective C. Thanks All.

+4  A: 

There's no built-in formatting operator to do that. If you wanted to convert it to a hexadecimal string, you could do:

NSString *str = [NSString stringWithFormat:"%x", theNumber];

To convert it to a binary string, you'll have to build it yourself:

NSMutableString *str = @"";
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
    // Prepend "0" or "1", depending on the bit
    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
Adam Rosenfield
A: 

Roughly:

-(void)someFunction
{
  NSLog([self toBinary:input]);
}

-(NSString *)toBinary:(NSInteger)input
{
  if (input == 1 || input == 0)
    return [NSString stringWithFormat:@"%d", input];
  [NSString stringWithFormat:@"%@%d", [self toBinary:input / 2], input % 2];
}
toast
What if the input is zero?
epatel
This fails if the input is 0 (or in fact if the last bit is 0), and it also allocates and deallocates N string objects, where N is the number of bits in the number. Not very efficient.
Adam Rosenfield
Hence roughly. But good catch.
toast
NSMutableString is derived from NSString, so insertString probably does the same thing as this.
toast
Except it doesn't. insertString:atIndex: inserts into the same buffer (and expands the buffer if necessary), whereas stringWithFormat allocates a new autoreleased NSString object.
Adam Rosenfield
Either way, it's a minor bit of throwaway code. The hit from doing it with NSMutableString vs. grabbing a new NSString is negligible enough. Not to mention that I did it recursively, which eats up stack space as well. The best that could be said is that it is functional (as in style of programming).
toast
Thanks to all for the suggestions/comments.