How to Convert NSInteger or NSString to a binary (string) value

后端 未结 2 940
野的像风
野的像风 2021-01-17 07:03

Anybody has some code in objective-c to convert a NSInteger or NSString to binary string?

example:

56 -> 111000

There are some code in stackoverflow

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 07:22

    Not sure which examples on SO didn't work for you, but Adam Rosenfield's answer here seems to work. I've updated it to remove a compiler warning:

    // 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);
    

提交回复
热议问题