0

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 that try do this, but it doesn´t work.

Thanks

1
  • Just a note, 111000 is technically a negative number if you're using 2's complement. 0111000 is positive (because of the leading 0) Commented Dec 15, 2009 at 17:38

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Tooting my own horn a bit here...

I've written a math framework called CHMath that deals with arbitrarily large integers. One of the things it does is allows the user to create a CHNumber from a string, and get its binary representation as a string. For example:

CHNumber * t = [CHNumber numberWithString:@"56"];
NSString * binaryT = [t binaryStringValue];
NSLog(@"Binary value of %@: %@", t, binaryT);

Logs:

2009-12-15 10:36:10.595 otest-x86_64[21918:903] Binary value of 56: 0111000

The framework is freely available on its Github repository.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.