objective-c 如何将 NSInteger 转换为二进制(字符串)值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/655792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Convert NSInteger to a binary (string) value
提问by redpicture
I am trying to figure out how to convert an NSInteger, say 56, to an NSString that is a binary representation of the original (int) value. Perhaps someone knows a formatting technique that can accept 56 and return "111000" within Objective C. Thanks All.
我想弄清楚如何将一个 NSInteger(比如 56)转换为一个 NSString,它是原始 (int) 值的二进制表示。也许有人知道可以接受 56 并在 Objective C 中返回“111000”的格式化技术。谢谢大家。
回答by Adam Rosenfield
There's no built-in formatting operator to do that. If you wanted to convert it to a hexadecimal string, you could do:
没有内置的格式化操作符可以做到这一点。如果要将其转换为十六进制字符串,可以执行以下操作:
NSString *str = [NSString stringWithFormat:@"%x", theNumber];
To convert it to a binary string, you'll have to build it yourself:
要将其转换为二进制字符串,您必须自己构建它:
NSMutableString *str = [NSMutableString stringWithFormat:@""];
for(NSInteger numberCopy = theNumber; numberCopy > 0; numberCopy >>= 1)
{
// Prepend "0" or "1", depending on the bit
[str insertString:((numberCopy & 1) ? @"1" : @"0") atIndex:0];
}
回答by redpicture
NSString * binaryStringFromInteger( int number )
{
NSMutableString * string = [[NSMutableString alloc] init];
int spacing = pow( 2, 3 );
int width = ( sizeof( number ) ) * spacing;
int binaryDigit = 0;
int integer = number;
while( binaryDigit < width )
{
binaryDigit++;
[string insertString:( (integer & 1) ? @"1" : @"0" )atIndex:0];
if( binaryDigit % spacing == 0 && binaryDigit != width )
{
[string insertString:@" " atIndex:0];
}
integer = integer >> 1;
}
return string;
}
I started from Adam Rosenfield's version, and modified to:
我从 Adam Rosenfield 的版本开始,并修改为:
- add spaces between bytes
- handle signed integers
- 在字节之间添加空格
- 处理有符号整数
Sample output:
示例输出:
-7 11111111 11111111 11111111 11111001
7 00000000 00000000 00000000 00000111
-1 11111111 11111111 11111111 11111111
2147483647 01111111 11111111 11111111 11111111
-2147483648 10000000 00000000 00000000 00000000
0 00000000 00000000 00000000 00000000
2 00000000 00000000 00000000 00000010
-2 11111111 11111111 11111111 11111110
回答by Benjamin Autin
Roughly:
大致:
-(void)someFunction
{
NSLog([self toBinary:input]);
}
-(NSString *)toBinary:(NSInteger)input
{
if (input == 1 || input == 0) {
return [NSString stringWithFormat:@"%d", input];
}
else {
return [NSString stringWithFormat:@"%@%d", [self toBinary:input / 2], input % 2];
}
}

