简体   繁体   English

为什么将字符串转换为数字时要减去“ 0”?

[英]Why is '0' subtracted when converting string to number?

I am new to C and I was looking for a custom function in C that would convert a string to an integer and I came across this algorithm which makes perfect sense except for one part. 我是C语言的新手,我一直在寻找C语言中的自定义函数,该函数会将字符串转换为整数,因此我碰到了这种算法,除了一部分之外,它非常有意义。 What exactly is the -'0' doing on this line n = n * 10 + a[c] - '0'; -'0'在这行上的确切-'0'n = n * 10 + a[c] - '0'; ?

    int toString(char a[]) {
      int c, sign, offset, n;

      if (a[0] == '-') {  // Handle negative integers
        sign = -1;
      }

      if (sign == -1) {  // Set starting position to convert
        offset = 1;
      }
      else {
        offset = 0;
      }

      n = 0;

      for (c = offset; a[c] != '\0'; c++) {
        n = n * 10 + a[c] - '0';
      }

      if (sign == -1) {
        n = -n;
      }

      return n;
    }

The algorithm did not have an explanation from where I found it, here . 该算法没有找到我在这里找到的解释。

The reason subtracting '0' works is that character code points for decimal digits are arranged sequentially starting from '0' up, without gaps. 之所以减去'0'是因为十进制数字的字符代码点从'0'开始依次排列,没有间隔。 In other words, the character code for '5' is greater than the character code for '0' by 5; 换句话说, '5'的字符代码比'0'的字符代码大5; character code for '6' is greater than the character code for '0' by 6, and so on. '6'的字符代码比'0'的字符代码大6,依此类推。 Therefore, subtracting the code of zero '0' from a code of another digit produces the value of the corresponding digit. 因此,从另一个数字的代码中减去零'0'的代码将产生相应数字的值。

This arrangement is correct for ASCII codes, EBSDIC, UNICODE codes of decimal digits, and so on. 此排列对于ASCII码,EBSDIC,十进制数字的UNICODE码等正确。 For ASCII codes, the numeric codes look like this: 对于ASCII码,数字代码如下所示:

'0' 48
'1' 49
'2' 50
'3' 51
'4' 52
'5' 53
'6' 54
'7' 55
'8' 56
'9' 57

Assuming x has a value in the range between '0' and '9' , x - '0' yields a value between 0 and 9 . 假设x的值在'0''9' ,则x - '0'的值在09之间。 So x - '0' basically converts a decimal digits character constant to its numerical integer value (eg, '5' to 5 ). 因此x - '0'基本上将十进制数字字符常量转换为其数字整数值(例如'5'5 )。

C says '0' to '9' are implementation defined values but C also guarantees '0' to '9' to be sequential values. C表示'0''9'是实现定义的值,但C也保证'0''9'为顺序值。

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

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