Jarret Hardie(谢谢!)昨天发布了这段代码,将 NSinteget 转换为二进制,并且运行良好,但我需要 8 位格式:
4 -> 00000100
修改此代码有什么想法吗?
// 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);
谢谢!!!!!!
最佳答案
这应该有效:
NSInteger theNumber = 56;
NSMutableString *str = [NSMutableString string];
NSInteger numberCopy = theNumber; // so you won't change your original value
for(NSInteger i = 0; i < 8 ; i++) {
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
numberCopy >>= 1;
}
NSLog(@"Binary version: %@", str);
关于objective-c - NSInteger 到 8 位格式的二进制(字符串)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1920213/