How to Convert NSInteger to a binary (string) value

烂漫一生 提交于 2019-11-27 20:14:17
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];
}
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:

  • 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
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];
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!