简体   繁体   English

将十进制数转换为二进制Objective-C

[英]Converting decimal number to binary Objective-C

Hi I have made an IOS app that converts binary, hexadecimal and decimal values. 嗨,我已经制作了一个转换二进制,十六进制和十进制值的IOS应用程序。 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. 它返回0和1但是太多了。 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... 并且下次不要忽略编译器的“与Integer转换不兼容的指针”提示......

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). 说明:Afaik,将对象分配给int,实际上将对象的地址分配给该整数,而不是字符串的内容(这是您想要的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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