0

I am facing problem with the objective c code to convert decimal to binary. When I enter small values it shows me the output.

For e.g. 12 -> 1010

But when I enters large numbers, it shows me the output as "10..." (includes dots in the output)

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

}

1 Answers1

0

There are two problems with your code.

1) Your label size is perhaps not able to accommodate your string. So check the length of it.

2) Your code will not support the conversion if value of x is large. The reason is that int has limited capacity. Check this question regarding memory size of in-built variable. So, consider making your string mutable and add 0s or 1s in it. 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);
Community
  • 1
  • 1
Prasad
  • 5,946
  • 3
  • 30
  • 36