在应届生笔试中,经常会遇到进制的转换,可能会以不同的格式返回,下面的代码就是十进制转成二进制,分别以数组和字符串的形式返回,代码如下:
//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;
}
网友评论