Generally used in the conversion is probably binary and decimal, decimal and hexadecimal, binary and hexadecimal conversion, as if the <stdlib.h> itoa function can do some conversion, but I still want to build wheels. Binary or hexadecimal go to decimal is very simple, for example, we want to convert the binary number 1011 decimal notation, you will find that 1011=101*2+1 and 101=10*2+1,10=1*2+0,1=0*2+1, that is to say 1011 ((((0*2+1) *2+ 0) +1) +1 to indicate that the result is automatically converted to decimal because the computer is based on the decimal in the calculation of this string of expressions. Hexadecimal is the same, the only difference is that the number of times should be 16 rather than 2.
intTodec (Char*a,intRadix) { inti; intDec =0; for(i =0; I < strlen (a); i++) { if(IsDigit (a[i)) Dec= Dec * radix + (A[i]-'0'); Else if(A[i] >='a'&&a[i] <='F') Dec= Dec * radix + (A[i]-'a'+Ten); Else if(A[i] >='A'&&a[i] <='F') Dec= Dec * radix + (A[i]-'A'+Ten); Else{printf ("error,please Check your input\n"); return-1; } } returnDec;}
Convert decimal to binary and octal actually just reverse the process above, for example, we want to convert 15 to binary, then we just use 15%2 to get the lowest bit of the number 1, but we (15/2)%2 got the second digit 1, sequentially down, We get a 15 binary representation of 1111. Hexadecimal to decimal is also based on the same principle.
voidDecto (intDecChar*arr,intRadix) { intI=0; inttmp; while(Dec >0) { if(tmp = Dec%radix) >=0&& tmp <Ten) Arr[i+ +] = tmp+'0'; Else if(TMP >=Ten&& tmp <= the) Arr[i++] ='A'+ (TMP-Ten); Elseprintf ("Error:radix bigger than hex"); Dec/=Radix; } Arr[i]=' /'; _strrev (arr);}
The conversion between binary and hexadecimal is also very simple, considering that a hexadecimal bit corresponds to four bits. You can create a list to record the correspondence between them (consider using a struct array as a list), and then look up the table when performing the conversion, it is worth noting that when the number of binary digits is not a multiple of 8, it is necessary to add 0 in the previous way to fill it into multiples of 8 (with strncpy, The Strcmp,strcat function should not be difficult). Since I suddenly do not want to write code, this conversion function will not put the code.
Binary conversion function