objective-c - NSInteger 到 8 位格式的二进制(字符串)值

标签 objective-c iphone binary

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/

相关文章:

haskell - 为什么包装 Data.Binary.Put monad 会导致内存泄漏? (第2部分)

javascript - 将javascript值转换为二进制以放入mysql中

iphone uitextfield - 焦点为空(简单吧?)

iPhone 开发者 handle

ios - UICollectionView 中的单边方向滚动?

ios - UISearchDisplayController 搜索栏不会关闭键盘?

java - 将十六进制字符串转换为二进制字符串 - Java

objective-c - 如何在 macOS 上取消反斜杠?

iphone - iOS自动引用计数(ARC)向后兼容性?

objective-c - ivars 必须用大括号括起来吗?