我會使用比特移位到達整數
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 >>= 1
是x = 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;
}
相關:http://stackoverflow.com/questions/7911651/decimal-to-binary(你需要轉換t他將字符串轉換爲NSString,但是目標c是c的一個超集... – geoffspear
這是一個相當離奇的算法。如果你想轉換成二進制字符,爲什麼不直接轉向角色? (至少使'result'成爲'long',因爲它可能是一個非常大的數字。) –
(並且在Java中也有更直接的方法來執行此操作) –