Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - To implement the conversion of unsigned integer to hexadecimal string representation, it is required that no functions can be called. The program is as follows, please comment, the more detailed the
To implement the conversion of unsigned integer to hexadecimal string representation, it is required that no functions can be called. The program is as follows, please comment, the more detailed the
To implement the conversion of unsigned integer to hexadecimal string representation, it is required that no functions can be called. The program is as follows, please comment, the more detailed the better.

#include

void intToHex(int ??n, char* s)

{

int temp = 0 ; A local variable, saving the intermediate result of the transformation

char t[128]; A temporary variable, recording the transformation result

int index = 0; Recording the current position of the current operation string, Start at 0

while(n) If n is not equal to 0, continue looping

{

temp = n % 16; temp equals n divided by 16 Remainder after

if(temp > 9) If the remainder is greater than 9

{

*(t + index++) = 'A' + temp - 10; If temp=10, then the current position=A, 11 is B, 12 is C, 13 is D, 14 is E, 15 is F, and index+1 points to the next bit of the string operation. If you know the ASCII code table , will be easy to understand, if you don’t know, then you must learn it. It is impossible to learn programming well without knowing ASCII

}

else if it is not greater than 9

{

*(t + index++) = '0' + temp; Then the number of this bit is written into the string, and the number is index+1 at the same time, pointing to the next bit of the string operation. This is also related to ASCII

}

n /= 16; Divide n by 16, and then assign the quotient to n

} When n is equal to 0 , the loop ends, the length of the string is recorded in index

*(t + index) = '\0'; Write the end of string mark at the current position

int j = 0;

for(int i = index - 1; i >= 0; --i) loop, assign each character of the transformation result to s for return to the main function

{

*(s + j++) = *(t + i);

}

*(s + j) = '\0 ';

}

int main(void)

{

char s[128]; declares a string for Save the result

int n; Integer variable, used to save the input data

printf("Input a unsigned integer: "); Display prompt for input on the screen

scanf("%d", &n); Use the keyboard to enter an integer and store it in the variable n

intToHex(n, s); Convert the integer in n into a hexadecimal string, and The result is stored in the string s

printf("Your input: %s\n", s); displays the transformation result

return 0;

}< /p>

There is another loophole in this program, that is, before calling intToHex, it should be judged that the input integer should be greater than 0, because the algorithm converts integers.