標籤:style blog color io for re
機器大小端判斷:
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 = 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 = -1212345;69 char str[10] = {‘\0‘}; //記得把str全填充為‘\0‘70 71 itoa(value, str);72 printf("The result is:%s\n", str);73 }