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

You may also like...

Leave a Reply

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