Convert decimal to binary

Helps to understand how binary count works:

- (NSString *)divideByTwo: (NSInteger) decimalNumber
{
    NSMutableString *binary = [[NSMutableString alloc]init];
    if (binary == 0) {
        [binary appendString:@"%@"];
    }
    while (decimalNumber > 0) {
        NSInteger rem = decimalNumber % 2;
        [binary appendString:[NSString stringWithFormat:@"%d", rem]];
        decimalNumber = decimalNumber / 2;
    }
    return binary;
}

There is also Any base converter on Github, which is a general case of base 2 conversion. It converts any decimal number to any base from 2 to 16 and mimics a stack behavior.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s