Convert Binary to Decimal in Objective C

我们两清 提交于 2019-12-19 21:25:36

问题


I have binary sequence in a string. How to convert it in decimal. Is there any built in function in Objective C ?


回答1:


NSString * b = @"1101";
long v = strtol([b UTF8String], NULL, 2);
NSLog(@"%ld", v); //logs 13

The downside of this is that it only appears to produce positive numbers.




回答2:


I couldn't find any built in function. So wrote simple C function according to the process we do for conversation.

(int) BinToInt(char *temp) {
int count, total, i, j, tmp;

total = 0;
count = strlen(temp);

for (i = 0; i <= count; i++) {
    if (temp[count-i] == '1') {
        tmp = 1;
        for (j = 1; j < i; j++)
            tmp *= 2;
        total += tmp;
    }
}



回答3:


[This code apparently needs no explaination]

(void)convertBinaryToNumeric{
    NSString *bin_Input = @"1010";
    NSString *reverseInput = [self reverseString:bin_Input];
    int dec_Output = 0;
    int dec_Counter = 0;

    for (int i=0; i<[reverseInput length]; i++) {
        dec_Output = [[reverseInput substringWithRange:NSMakeRange(i, 1)] intValue] * [self multipliesByTwo:i];
        dec_Output = dec_Counter + dec_Output;
        dec_Counter = dec_Output;
    }
    NSLog(@"Bin:%@ Dec:%d",bin_Input,dec_Output);
}

(NSString *)reverseString:(NSString *)inputStr{
    NSMutableString *revStr = [[NSMutableString alloc]initWithString:@""];
    for (int i=[inputStr length]-1; i>=0; i--) {
        [revStr appendString:[inputStr substringWithRange:NSMakeRange(i, 1)]];
    }
    return revStr;
}

(int)multipliesByTwo:(int)number{
    if(number == 0){
        return 1;
    }else{
        int bin_value = 2;
        int multipleBy=0;
        for (int i=1; i<=number; i++) {
            if(multipleBy == 0){
                multipleBy = bin_value;
            }else{
                multipleBy = multipleBy *2;
            }
        }
        return multipleBy;
    }
    return 0;
}


来源:https://stackoverflow.com/questions/4618403/convert-binary-to-decimal-in-objective-c

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