我刚刚找到了一个二进制版本的NSString to Print in in binary format,但我想知道是否有一个灵活的版本。
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // equals 11110000
let stringOfInvertedBits = String(invertedBits, radix: 2) // convert to string in binary
print(stringOfInvertedBits) // 11110000radix: 2表示二进制,radix: 8表示八进制,依此类推...
发布于 2016-01-08 16:07:59
这是@Paul Griffiths答案的修改,它更快更有效,因为它避免了不断地重新分配NSString
- (NSString *)formatStringFromInt:(int)value withRadix:(int)radix
{
if (value == 0)
return @"0";
if (radix < 2 || radix > 36)
radix = 10;
const unsigned buffsize = 64;
unichar buffer[buffsize];
unsigned offset = buffsize;
static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int absValue = abs(value);
while (absValue > 0) {
buffer[--offset] = (unichar)digits[absValue % radix];
absValue /= radix;
}
if (value < 0)
buffer[--offset] = '-';
return [[NSString alloc] initWithCharacters:buffer + offset
length:buffsize - offset];
}产生:
2016-01-08 11:52:53.644 stringformatprefix[7560:606490] D
2016-01-08 11:52:53.645 stringformatprefix[7560:606490] 13
2016-01-08 11:52:53.645 stringformatprefix[7560:606490] -15
2016-01-08 11:52:53.645 stringformatprefix[7560:606490] -23
2016-01-08 11:52:53.645 stringformatprefix[7560:606490] 1101发布于 2016-01-08 11:01:52
下面是一个简单的修改:
#import <Foundation/Foundation.h>
NSString * getBitStringForInt(const int value, const int radix) {
static const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ( radix < 2 || radix > 36 ) {
return NULL;
}
NSString *bits = @"";
int absValue = abs(value);
while ( absValue ) {
bits = [NSString stringWithFormat:@"%c%@", digits[absValue % radix], bits];
absValue /= radix;
}
if ( value < 0 ) {
bits = [NSString stringWithFormat:@"-%@", bits];
}
return bits;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString * val = getBitStringForInt(13, 16);
NSLog(@"%@", val);
val = getBitStringForInt(13, 10);
NSLog(@"%@", val);
val = getBitStringForInt(-13, 8);
NSLog(@"%@", val);
val = getBitStringForInt(-13, 5);
NSLog(@"%@", val);
val = getBitStringForInt(13, 2);
NSLog(@"%@", val);
}
return 0;
}带输出:
2016-01-07 21:59:59.144 TestCmdLine[49904:18135090] D
2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] 13
2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] -15
2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] -23
2016-01-07 21:59:59.145 TestCmdLine[49904:18135090] 1101
Program ended with exit code: 0https://stackoverflow.com/questions/34652499
复制相似问题