简体   繁体   中英

Converting decimal number to binary Objective-C

Hi I have made an IOS app that converts binary, hexadecimal and decimal values. It all works fine except for my decimal to binary conversion. Here is what I have. It returns 0s and 1s but far too many. Can anyone tell me why this is or help me with a better method?

NSString *newDec = [display text]; //takes user input from display
NSString *string = @"";
NSUInteger x = newDec;
int i = 0;
while (x > 0) {
    string = [[NSString stringWithFormat:@"%u", x&1] stringByAppendingString:string];
    x = x>> 1;
    ++i;
}
display.text = string; //Displays result in ios text box 

Try this:

NSUInteger x = [newDec integerValue];

And next time don't ignore the Compiler's "Incompatible pointer to Integer conversion" hint...

Explanation: Afaik, assigning an object to an int, actually assigns the address of the object to that integer, not the content of the string (which is what you want).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM