十进制到二进制转换方法Objective-C

您好我想在Objective-C中做一个十进制的二进制数字转换器,但已经不成熟…我有以下方法到目前为止,这是一个类似的方法尝试从Java翻译。 任何帮助,使这个方法的工作非常感谢。

+(NSString *) DecToBinary: (int) decInt { int result = 0; int multiplier; int base = 2; while(decInt > 0) { int r = decInt % 2; decInt = decInt / base; result = result + r * multiplier; multiplier = multiplier * 10; } return [NSString stringWithFormat:@"%d",result]; 

我将使用位移到达整数的每一位

 x = x >> 1; 

将位向左移动一位,十进制数13代表1101位,所以向右移动会产生110 – > 6。

 x&1 

是用1掩蔽x的位

  1101 & 0001 ------ = 0001 

结合这些行将从最低位迭代到最高位,并且我们可以将此位作为格式化的整数添加到string中。

对于unsigned int可能是这样的。

 #import <Foundation/Foundation.h> @interface BinaryFormatter : NSObject +(NSString *) decToBinary: (NSUInteger) decInt; @end @implementation BinaryFormatter +(NSString *)decToBinary:(NSUInteger)decInt { NSString *string = @"" ; NSUInteger x = decInt; while (x>0) { string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string]; x = x >> 1; } return string; } @end int main(int argc, const char * argv[]) { @autoreleasepool { NSString *binaryRepresentation = [BinaryFormatter decToBinary:13]; NSLog(@"%@", binaryRepresentation); } return 0; } 

这段代码将返回1101 ,即13的二进制表示。


do-while较短的forms, x >>= 1x = x >> 1的简写forms:

 +(NSString *)decToBinary:(NSUInteger)decInt { NSString *string = @"" ; NSUInteger x = decInt ; do { string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string]; } while (x >>= 1); return string; } 
 NSMutableArray *arr = [[NSMutableArray alloc]init]; //i = input, here i =4 i=4; //r = remainder //q = quotient //arr contains the binary of 4 in reverse order while (i!=0) { r = i%2; q = i/2; [arr addObject:[NSNumber numberWithInt:r]]; i=q; } NSLog(@"%@",arr); // arr count is obtained to made another array having same size c = arr.count; //dup contains the binary of 4 NSMutableArray *dup =[[NSMutableArray alloc]initWithCapacity:c]; for (c=c-1; c>=0; c--) { [dup addObject:[arr objectAtIndex:c]]; } NSLog(@"%@",dup);