c - ASCII and printf -
i have little (big, dumb?) question int , chars in c. rememeber studies "chars little integers , viceversa," , that's okay me. if need use small numbers, best way use char type.
but in code this:
#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; }
i can use argument every number want. 0-127 obtain expected results (the standard ascii table) bigger or negative numbers seems work...
here example:
-181 -> k -182 -> j 300 -> , 301 -> -
why? seems me it's cycling around ascii table, don't understand how.
when pass int corresponding "%c" conversion specifier, int converted unsigned char , written.
the values pass being converted different values when outside range of unsigned (0 uchar_max). system working on has uchar_max == 255.
when converting int unsigned char:
- if value larger uchar_max, (uchar_max+1) subtracted value many times needed bring range 0 uchar_max.
- likewise, if value less zero, (uchar_max+1) added value many times needed bring range 0 uchar_max.
therefore:
(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 == '-'
Comments
Post a Comment