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
2009-03-17 20:13:11
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
2009-03-17 20:13:51
What if the input is zero?
epatel
2009-03-17 20:16:57
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
2009-03-17 20:27:06
Hence roughly. But good catch.
toast
2009-03-17 20:35:11
NSMutableString is derived from NSString, so insertString probably does the same thing as this.
toast
2009-03-17 20:40:04
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
2009-03-17 20:46:06
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
2009-03-17 20:58:04
Thanks to all for the suggestions/comments.
2009-03-19 00:38:26