How to convert a NSInteger to a binary string

I've seen a lot of question on the internet about this topic.

Here it is my preferred solution:

 

 

NSInteger theNumber = 56; // setup here your value….

NSMutableString *str = [NSMutableString string];

for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)

{

    // Prepend "0" or "1", depending on the bit

    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];

}


NSLog(@"Binary version: %@", str);

 

Gg1

Posted by at June 6, 2011
Filed in category: iphone, Mac OS X, Tower of Babel, and tagged with: , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

%d bloggers like this: