C language design realizes mutual conversion between hexadecimal and decimal numbers

1. Convert hexadecimal numbers to decimal numbers

1. Design a C language code to convert hexadecimal numbers such as 0xFEFF to decimal

The following is an example of C language code to convert a hexadecimal number to decimal:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char hexNum[10];  // 存储输入的十六进制数
    int decNum;       // 存储转换后的十进制数

    printf("请输入一个十六进制数:");
    scanf("%s", hexNum);//例如0xFEFF或0x00800000

    // 使用 strtol 函数将十六进制数转换为十进制数
    decNum = strtol(hexNum, NULL, 16);

    printf("转换后的十进制数为:%d\n", decNum);

    return 0;
}

In the above code, we used strtolthe function to convert from hexadecimal to decimal. strtolThe first parameter of the function is the string to be converted, the second parameter is a pointer to a character pointer to store the remainder without conversion (if any), and the third parameter specifies the base of the conversion , where 16 is used for hexadecimal.

You can enter a hexadecimal number such as "0xFEFF" when the program is running, and it will output the converted decimal number 65279.

请输入一个十六进制数:0xFEFF
转换后的十进制数为:65279
请输入一个十六进制数:0x00800000
转换后的十进制数为:8388608

 2. Convert decimal numbers to hexadecimal numbers

1. Design a C language code to convert decimal to hexadecimal number and the form of hexadecimal number is 0x0000000, this form:

The following is a C language code example for converting a decimal number to a hexadecimal number of the form 0x0000000:

#include <stdio.h>
#include <stdlib.h>

void printHex(int decimalValue) {
    printf("Hex: 0x%X\n", decimalValue);
}

int main() {
    char tmp_decimalValue[10]; // 十进制数
    printf("请输入一个十进制数:");
    scanf("%s", tmp_decimalValue);//例如65279
    int decimalValue = atoi(tmp_decimalValue);
    printHex(decimalValue);

    return 0;
}

In the above code, we define a function printHex()to print the hexadecimal number format like 0x0000000. We use printf()the function's format string to specify the output format, which %Xmeans print a hexadecimal number.

For the decimal number 65279, the above code would output:

请输入一个十进制数:65279
Hex: 0xFEFF

3. Summary

Through the above two code examples, the study assumes different data and performs the conversion process;

Guess you like

Origin blog.csdn.net/qq_50635297/article/details/131209256