4

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

Ruchit Patel
  • 1,030
  • 1
  • 12
  • 24

3 Answers3

21
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.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • If you want to use the leftmost bit as the sign bit (i.e. `0001`=1 and `1001`=-1) then you can just use `[str hasPrefix:@"1"]`. Otherwise you can use other algorithms to check if the string corresponds to a negative – Arc676 May 13 '15 at 12:48
-1

[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;
}
Hugo Yates
  • 2,081
  • 2
  • 26
  • 24
-1

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;
    }
}
Ruchit Patel
  • 1,030
  • 1
  • 12
  • 24