2011-01-06 8 views

답변

-1

내장 함수를 찾을 수 없습니다. 그래서 우리가 대화를 위해하는 과정에 따라 간단한 C 함수를 작성했습니다.

(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; 
    } 
} 
20
NSString * b = @"1101"; 
long v = strtol([b UTF8String], NULL, 2); 
NSLog(@"%ld", v); //logs 13 

이것의 단점은 단지 양수를 생산하는 표시이다.

+0

왼쪽 비트를 부호 비트 (즉, '0001'= 1 및 '1001'= -1)로 사용하려면'[str hasPrefix : @ "1"]'을 사용할 수 있습니다. 그렇지 않으면 다른 알고리즘을 사용하여 문자열이 음수에 해당하는지 확인하십시오 – Arc676

-1

그들은 이제 목표 - C에서 숙제를 설정하는

(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; 
} 
+0

그것은 내 자신의 논리에 도움이 될 수 있습니다. –