gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 03:46:51 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com