美文网首页
十进制转成二进制,分别数组和字符串的形式返回

十进制转成二进制,分别数组和字符串的形式返回

作者: subject_2619 | 来源:发表于2017-09-11 09:08 被阅读0次

    在应届生笔试中,经常会遇到进制的转换,可能会以不同的格式返回,下面的代码就是十进制转成二进制,分别以数组和字符串的形式返回,代码如下:

    //10进制转成2进制,返回数组
    -(NSMutableArray*)convertBinary:(int) decimal{
        
        NSMutableArray *tmp = [NSMutableArray arrayWithObjects:[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],[NSNumber numberWithInt:0],nil];
        NSUInteger index=7;
        int remainder =0;//余数
        int divisor = decimal;//整数
        while(divisor > 0) {
            remainder = divisor%2;
            [tmp replaceObjectAtIndex: index withObject:[NSNumber numberWithInt:remainder]];
            divisor=divisor/2;
            index--;
        }
        return tmp;
    }
    
    //十进制转二进制,返回字符串
    - (NSString*)toBinarySystemWithDecimalSystem:(int)num length:(int)length
    {
        int remainder =0;//余数
        int divisor =0;//除数
        NSString* prepare =@"";
        while(true)
        {
            remainder = num%2;
            divisor = num/2;
            num = divisor;
            prepare = [prepare stringByAppendingFormat:@"%d",remainder];
            if(divisor == 0){
                break;
            }
        }
        //倒序输出
        NSString* result = @"";
        for(int i = length -1; i >=0; i --){
            if(i <= prepare.length-1) {
                result = [result stringByAppendingFormat:@"%@",
                          [prepare substringWithRange:NSMakeRange(i ,1)]];
            }else{
                result = [result stringByAppendingString:@"0"];
            }
        }
        NSLog(@"result=%@",result);
        return result;
    }
    

    相关文章

      网友评论

          本文标题:十进制转成二进制,分别数组和字符串的形式返回

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