C language-advanced programming questions (character string, hexadecimal conversion)

C language-advanced programming questions (character string, hexadecimal conversion)

Enter a hexadecimal numeric string. (Conversion of hexadecimal system)
Input:
0xA
output
10.
Basic idea: start with the input, and consider it as a string, but a special point (a hexadecimal number), then we happen to be able to use this hexadecimal input The format is used as a loop judgment condition, and only needs to be changed slightly. The next step is the highlight, the hexadecimal to decimal algorithm, which performs calculations on each digit of hexadecimal (after 0x)-for example: 0xAA corresponds to The decimal number is equal to (from right to left) A 16^0 plus A 16 to the power of 1, and the result is 170. (What is the weight of enenenenen, hahaha, the weight of hexadecimal is 16, and the weight of decimal is 10. , And so on), the overall idea can be written down. No one asked again, "Brother Fei, how can I get the power?", then the function pow (base, power) in the <math.h> header file must be used, pay attention! note! note! Its return value type is double type, and our base conversion is generally an integer operation, so remember to force the conversion . (Format (type) pow( , )).
In hexadecimal, A=10, B=11 and so on to F=15.

#include<stdio.h>
#include<string.h>
#include<math.h>
int Ox_D(char ch[]){
    
    
	int ten = 0;
	for (int i = strlen(ch) - 1,j=0;ch[i]!='x';--i,++j){
    
    
		if (ch[i] >= '0'&&ch[i] <= '9'){
    
    
			ten = ten + (ch[i] - 48)*(int)pow(16, j);//字符型数字和十进制数差值为48
		}
		else if (ch[i]=='A'||ch[i]=='a'){
    
    
			ten = ten + 10*(int)pow(16, j);
		}
		else if (ch[i] == 'B' || ch[i] == 'b'){
    
    
			ten = ten + 11 * (int)pow(16, j);
		}
		else if (ch[i] == 'C' || ch[i] == 'c'){
    
    
			ten = ten + 12 * (int)pow(16, j);
		}
		else if (ch[i] == 'D' || ch[i] == 'd'){
    
    
			ten = ten + 13 * (int)pow(16, j);
		}
		else if (ch[i] == 'E' || ch[i] == 'e'){
    
    
			ten = ten + 14 * (int)pow(16, j);
		}
		else {
    
    
			ten = ten + 15 * (int)pow(16, j);
		}
	}
	return ten;
}
int main(){
    
    
		char ch[5000];
		while (scanf("%s", ch) != EOF){
    
    
			printf("%d\n", Ox_D(ch));
		}
	return 0;
}

Okay, let's stop here. I will update the program code from time to time. I wrote it myself. It may not be perfect. It is also a kind of supervision for myself. If you like, you can pay attention to a wave of events. By the way, I will like it. Hehe.

Guess you like

Origin blog.csdn.net/qq_45841205/article/details/109439391