有人在objective-c中有一些代碼將NSInteger或NSString轉換爲二進制字符串?如何將NSInteger或NSString轉換爲二進制(字符串)值
例如:
56 - > 111000
有計算器中試圖做一些這方面的代碼,但它doesn't工作。
感謝
有人在objective-c中有一些代碼將NSInteger或NSString轉換爲二進制字符串?如何將NSInteger或NSString轉換爲二進制(字符串)值
例如:
56 - > 111000
有計算器中試圖做一些這方面的代碼,但它doesn't工作。
感謝
不知道這對SO例子並不爲你工作,但Adam Rosenfield's answer here似乎工作。我已經更新了其刪除編譯器警告:
// Original author Adam Rosenfield... SO Question 655792
NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
NSLog(@"Binary version: %@", str);
它的工作原理 謝謝! – oscarp 2009-12-15 17:08:14
Tooting我自己的喇叭有點這裏...
我已經寫了叫CHMath
數學框架,具有任意大整數的交易。它所做的一件事是允許用戶從一個字符串創建一個CHNumber
,並將其二進制表示形式作爲一個字符串。例如:
CHNumber * t = [CHNumber numberWithString:@"56"];
NSString * binaryT = [t binaryStringValue];
NSLog(@"Binary value of %@: %@", t, binaryT);
日誌:
2009-12-15 10:36:10.595 otest-x86_64[21918:903] Binary value of 56: 0111000
該框架是its Github repository免費獲得。
真棒圖書館。 – uchuugaka 2013-12-24 02:06:52
請注意,如果你使用2的補碼,'111000'在技術上是一個負數。 '0111000'是正數(因爲領先的0) – 2009-12-15 17:38:53