简体   繁体   English

十进制转换为二进制输出

[英]conversion of decimal to binary output

I am facing problem with the objective c code to convert decimal to binary. 我面临的目标C代码将十进制转换为二进制的问题。 When I enter small values it shows me the output. 当我输入较小的值时,它将显示输出。

For eg 12 -> 1010 例如12-> 1010

But when I enters large numbers, it shows me the output as "10..." (includes dots in the output) 但是,当我输入大量数字时,它将显示输出为“ 10 ...”(输出中包括点)

Please help me. 请帮我。

My program is as follows: 我的程序如下:

NSUInteger x = [newDec integerValue];
//int y[30];
int i=0;
int m =1;

while (x != 0) {
    int mod = x % 2;
    x /= 2;
    i = i + mod * m;
    m = m * 10;

                       string = [NSString stringWithFormat:@"%d", i];

}

There are two problems with your code. 您的代码有两个问题。

1) Your label size is perhaps not able to accommodate your string. 1)您的标签大小可能无法容纳您的字符串。 So check the length of it. 因此,请检查其长度。

2) Your code will not support the conversion if value of x is large. 2)如果x的值很大,您的代码将不支持转换。 The reason is that int has limited capacity. 原因是int容量有限。 Check this question regarding memory size of in-built variable. 检查有关内置变量的内存大小的问题 So, consider making your string mutable and add 0s or 1s in it. 因此,请考虑使您的字符串可变,并在其中添加0或1。 I am attaching my snippet of code. 我附上我的代码片段。

NSMutableString *string = [[NSMutableString alloc] init];
while (x != 0) {
    int mod = x % 2;
    x /= 2;
    [string insertString:[NSString stringWithFormat:@"%d", mod] atIndex:0];
}
NSLog(@"String = %@", string);

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

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