I would use bit shifting to reach each bit of the integer
x = x >> 1;
moves the bits by one to the left, the decimal 13 is represente in bits as 1101, so shifting it to the right turns creates 110 -> 6.
x&1
is the bit masking x with 1
1101
& 0001
------
= 0001
Combined these lines will iterate form the lowest to highest bit and we can add this bit as formatted integer to a string.
For unsigned int it could be this.
#import <Foundation/Foundation.h>
@interface BinaryFormatter : NSObject
+(NSString *) decToBinary: (NSUInteger) decInt;
@end
@implementation BinaryFormatter
+(NSString *)decToBinary:(NSUInteger)decInt
{
NSString *string = @"" ;
NSUInteger x = decInt;
while (x>0) {
string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string];
x = x >> 1;
}
return string;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *binaryRepresentation = [BinaryFormatter decToBinary:13];
NSLog(@"%@", binaryRepresentation);
}
return 0;
}
this code will return 1101, the binary representation of 13.
Shorter form with do-while, x >>= 1 is the short form of x = x >> 1:
+(NSString *)decToBinary:(NSUInteger)decInt
{
NSString *string = @"" ;
NSUInteger x = decInt ;
do {
string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string];
} while (x >>= 1);
return string;
}
resultbe along, since it's apt to be a very large number.)