Decimal to Binary conversion method Objective-C

时光毁灭记忆、已成空白 提交于 2019-12-08 02:43:27

问题


Hi I am trying to make a Decimal to binary number converter in Objective-C but have been unsucessful... I have the following method so far which is an attempted translation from Java for a similar method. Any help to make this method work is much appreciated.

 +(NSString *) DecToBinary: (int) decInt
{
    int result = 0;
    int multiplier;
    int base = 2;
    while(decInt > 0)
    {
        int r = decInt % 2;
        decInt = decInt / base;
        result = result + r * multiplier;
        multiplier = multiplier * 10;
    }
return [NSString stringWithFormat:@"%d",result];

回答1:


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;
}



回答2:


NSMutableArray *arr = [[NSMutableArray alloc]init];

//i = input, here i =4
i=4;

//r = remainder
//q = quotient

//arr contains the binary of 4 in reverse order
while (i!=0)
{
    r = i%2;
    q = i/2;
    [arr addObject:[NSNumber numberWithInt:r]];
    i=q;
}
NSLog(@"%@",arr);

// arr count is obtained to made another array having same size
c = arr.count;

//dup contains the binary of 4
NSMutableArray *dup =[[NSMutableArray alloc]initWithCapacity:c];    

for (c=c-1; c>=0; c--)
{
    [dup addObject:[arr objectAtIndex:c]];
}

NSLog(@"%@",dup);


来源:https://stackoverflow.com/questions/22366159/decimal-to-binary-conversion-method-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!