关于C中的int和chars,我有一个小的(大的,愚蠢的)问题.我记得我的研究中"chars是小整数和反之亦然",这对我来说没问题.如果我需要使用小数字,最好的方法是使用char类型.
但是在这样的代码中:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int i= atoi(argv[1]);
printf("%d -> %c\n",i,i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用我想要的每个数字作为参数.因此,使用0-127我获得了预期的结果(标准ASCII表),但即使有更大或更大的数字,它似乎工作...
这是一些例子:
-181 -> K
-182 -> J
300 -> ,
301 -> -
Run Code Online (Sandbox Code Playgroud)
为什么?在我看来,它在ascii表周围循环,但我不明白如何.
传递对应于"%c"转换说明符的int时,int将转换为unsigned char,然后写入.
传递的值超出无符号范围(0到UCHAR_MAX)时,将转换为不同的值.您正在使用的系统可能具有UCHAR_MAX == 255.
将int转换为unsigned char时:
因此:
(unsigned char)-181 == (-181 + (255+1)) == 75 == 'K'
(unsigned char)-182 == (-182 + (255+1)) == 74 == 'J'
(unsigned char)300 == (300 - (255+1)) == 44 == ','
(unsigned char)301 == (301 - (255+1)) == 45 == '-'
Run Code Online (Sandbox Code Playgroud)