Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
695 views
Welcome To Ask or Share your Answers For Others

1 Answer

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...