美文网首页
二进制与十进制的相互转换

二进制与十进制的相互转换

作者: WindFlyCloud | 来源:发表于2018-05-17 17:31 被阅读0次

十进制转二进制

/**
 十进制转换为二进制
 
 @param decimal 十进制数
 @return 二进制数
 */
- (NSString *)getBinaryByDecimal:(NSInteger)decimal {
    
    NSString *binary = @"";
    while (decimal) {
        
        binary = [[NSString stringWithFormat:@"%d", decimal % 2] stringByAppendingString:binary];
        if (decimal / 2 < 1) {
            
            break;
        }
        decimal = decimal / 2 ;
    }
    if (binary.length != 7) {
        
        NSMutableString *mStr = [[NSMutableString alloc]init];;
        for (int i = 0; i < 7 - binary.length; i++) {
            
            [mStr appendString:@"0"];
        }
        binary = [mStr stringByAppendingString:binary];
    }
    DLog(@"bin---%@",binary);
    return binary;
}

二进制转十进制

/**
 二进制转十进制

 @param str <#str description#>
 @return <#return value description#>
 */
- (NSString *) turnBinarytoDecimal:(NSString *)str{
    int sum = 0;
    for (int i = 0; i < str.length; i++) {
        sum *= 2;
        char c = [str characterAtIndex:i];
        sum += c - '0';
    }
    return [NSString stringWithFormat:@"%d",sum];
}

//  二进制转十进制

- (NSString *)toDecimalSystemWithBinarySystem:(NSString *)binary

{
    int ll = 0 ;
    int  temp = 0 ;
    for (int i = 0; i < binary.length; i ++)
    {
        temp = [[binary substringWithRange:NSMakeRange(i, 1)] intValue];
        temp = temp * powf(2, binary.length - i - 1);
        ll += temp;
    }
    
    NSString * result = [NSString stringWithFormat:@"%d",ll];
    return result;
    
}

相关文章

网友评论

      本文标题:二进制与十进制的相互转换

      本文链接:https://www.haomeiwen.com/subject/jxhidftx.html