开发者

How to do string related problem

I am making a binary to decimal number converter on iphone. having some problem when i trying to take each single digit from a number and do calculation. I tried char, characterAtIndex but they all failed to do calculation or i got the syntax completely wrong. Can anyone show me how to do such cast or th开发者_JAVA百科ere is an easier approach?


Your problem is getting numbers from strings?

The easiest way to get an integer from a character is to use the ascii table, like this:

NSString *stringOfNums = @"15";
char c;
int num;
for (int i = 0; i < [stringOfNums length]; ++i) {
    c = [stringOfNums characterAtIndex:i];
    num = c - 48; // 0 is 48 in ascii table
    printf("\nchar is %c and num is %d", c, num);
}

The advantage of this method is that you can validate on a char-by-char basis that each falls in a range of 48 through 57, the ascii digits.

Or you could do the conversion in one step using NSNumberFormatter, as described here: How to convert an NSString into an NSNumber

As for the binary-decimal conversion, does your formula work on paper? Get that right first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜