Analysis of C language examples

Keywords: C

Turbo C 2.0 is used as the compiling environment in the essence of C language case analysis. However, this compiler has a long history. Newer compilers don't support some examples in the book well. When learning, they take notes at the same time.

Example 18: convert an unsigned integer to any d-BASE (d is between 2 and 16).

Main idea: to find the remainder of d for the unsigned integer n, we can get the lowest digit of d-BASE of N, and repeat the above steps until n is 0. According to this, we can get the lowest to the highest digit of the d-BASE representation of N, and convert the digit into character to get the result.

 1 /*Function trans converts the unsigned integer n to the D-BASE (2 < = d < = 16)
 2 Represented string s*/
 3 #define M sizeof(unsigned int)*8 //Converts an unsigned number to a string, 8 bits per character
 4 int trans(unsigned n, int d, char s[])
 5 {
 6     static char digits[] = "012345678ABCDEF";
 7     char        buf[M+1];
 8     int         j, i = M;
 9     
10     if(d<2 || d>16)
11     {
12         s[0] = '\0'; //End bit of string
13         return 0;
14     }
15     
16     buf[i] = '\0';
17     do
18     {
19         buf[--i] = digits[n%d];
20         n /= d;
21     }while(n);
22     /*Copy string from working array to s*/
23     for(j=0; (s[j]=buf[i]) != '\0'; j++,i++);
24     return j;
25 }
26 
27 int main()
28 {
29     unsigned int num = 0;
30     int          scale[] = {2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,1}; //Base 2~16
31     char         str[33];
32     int          i;
33     clrscr();   //The clear screen function is only available in Turbo The solution used in is to change it to system("cls")
34                 //But whether the program is tested by this sentence has no effect on the result.
35     puts("Please input a number to translate:");
36     scanf("%d", &num);
37     printf("The number you input is %d.\nThe translation result are:\n",num);
38     //This loop is used to test and display the result of converting the same unsigned integer into different bases.
39     for(i=0; i<sizeof(scale)/sizeof(scale[0]); i++)
40     {
41         if(trans(num, scale[i], str))
42             printf("%5d = %s(%d)\n",num,str,scale[i]);
43         else
44             printf("%5d => (%d) Error!\n",num,scale[i]);
45     }
46     printf("\nPress any key to quit...\n");
47     return 0;
48 }

Posted by maGGot_H on Wed, 01 Jan 2020 08:04:06 -0800