首页 > 代码库 > c基础总结

c基础总结

机器大小端判断:

 1 #include <stdio.h> 2  3 typedef union{ 4     char x; 5     int  i;   6 }un; 7  8 int main() 9 {10     un tt; 11     tt.i = 1;12 13     if(tt.x == 1)14     {   15         printf("little-endian !\n");16     }   17     else18     {   19         printf("big-endian !\n");20     }   21     printf("tt.x = %d\n", tt.x);22     return 0;23 }

实现atoi() , itoa()

 1 #include <stdio.h> 2  3 int my_atoi(char *s) 4 { 5     int sign = 1, num = 0; 6     switch(*s) 7     { 8         case -: 9             sign = -1;10             s++;11             break;12         case +:13             s++;14             break;15         default:16             break;17     }18 19     while((*s)!=\0)20     {21         num = num*10 + (*s-0);22         s++;23     }24 25     return num*sign;26 }27 void itoa(int value, char *str)28 {29     int i, j;30     char tmp = 0;31     if(value<0)32     {33         str[0] = -;34         value = http://www.mamicode.com/0-value;35     }36 37     //在这里已经被逆序了;38     for(i=1;value>0;i++,value/=10)39     {40         str[i] = value%10 + 0;41     }42     //数组再逆序一次43     for(j=i,i=1;i<=j/2;i++)44     {45         tmp = str[i];46         str[i] = str[j-i];47         str[j-i] = tmp;48     }49 /*50     for(j=i-1,i=1; j-i>=1; j--,i++) //将数字字符反序存放51     {52         str[i] = str[i]^str[j];53         str[j] = str[i]^str[j];54         str[i] = str[i]^str[j];55     }56 */57     if(str[0] != -) //如果不是负数,则需要把数字字符下标左移一位,即减158     {59         for(i=0; str[i+1]!=\0; i++)60             str[i] = str[i+1];61         str[i] = \0;62     }63 64 }65 66 void main()67 {68     int value = http://www.mamicode.com/-1212345;69     char str[10] = {\0}; //记得把str全填充为‘\0‘70 71     itoa(value, str);72     printf("The result is:%s\n", str);73 }