views:

224

answers:

1

Hi

Jarret Hardie (thanks !) post this code yesterday to convert a NSinteget to binary, and works perfectly, but i need in 8bit format:

4 -> 00000100

any ideas to modify this code?

// Original author Adam Rosenfield... SO Question 655792
NSInteger theNumber = 56;
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);

Thanks !!!!!!

+1  A: 

This should work:

NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
NSInteger numberCopy = theNumber; // so you won't change your original value
for(NSInteger i = 0; i < 8 ; i++) {
    // Prepend "0" or "1", depending on the bit
    [str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
    numberCopy >>= 1;
}

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