2014-03-12 18 views
2

嗨我想在Objective-C中製作一個十進制到二進制數字轉換器,但一直沒有成功......我有以下方法,這是從Java嘗試轉換爲一個類似的方法。任何幫助,使這種方法的工作非常感謝。十進制到二進制轉換方法Objective-C

+(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]; 
+1

相關:http://stackoverflow.com/questions/7911651/decimal-to-binary(你需要轉換t他將字符串轉換爲NSString,但是目標c是c的一個超集... – geoffspear

+0

這是一個相當離奇的算法。如果你想轉換成二進制字符,爲什麼不直接轉向角色? (至少使'result'成爲'long',因爲它可能是一個非常大的數字。) –

+0

(並且在Java中也有更直接的方法來執行此操作) –

回答

9

我會使用比特移位到達整數

x = x >> 1; 

的每個比特由一個移動的位的左側,十進制13是represente以位爲1101,所以它轉移到右轉彎創建110 - > 6.

x&1 

是被1

1101 
& 0001 
------ 
= 0001 
的比特掩蔽X

合併這些行將從最低位迭代到最高位,我們可以將此位作爲格式化整數添加到字符串中。

對於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-而二進制表示,x >>= 1x = x >> 1短形式:

+(NSString *)decToBinary:(NSUInteger)decInt 
{ 
    NSString *string = @"" ; 
    NSUInteger x = decInt ; 
    do { 
     string = [[NSString stringWithFormat: @"%lu", x&1] stringByAppendingString:string]; 
    } while (x >>= 1); 
    return string; 
} 
+0

長版本中變量i的原因是什麼?看起來它並沒有在循環中用於增加? – Arne

0
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);