C language base conversion (full)


Convert to binary:

Decimal to binary (10➤2)

A decimal number can be converted to a binary number by continuously taking the remainder of 10 and shifting the binary digits to the left. Specific steps are as follows:

1. Define an array to store binary numbers.
2. Define a variable to record the array subscript.
3. Loop through the remainder of 10 until 10 is 0.
4. Each time the remainder is taken, it is stored in the array.
5. Add 1 to the array subscript after each remainder is taken.
6. Finally, output the array in reverse order.

code show as below

#include <stdio.h>

int main()
{
    
    
    int decimal, remainder, index = 0;
    int binary[32];
    
    printf("请输入一个十进制数:");
    scanf("%d", &decimal);
    
    while (decimal != 0)
    {
    
    
        remainder = decimal % 2;
        binary[index] = remainder;
        index++;
        decimal /= 2;
    }
    
    printf("转换为二进制数为:");
    for (int i = index - 1; i >= 0; i--)
    {
    
    
        printf("%d", binary[i]);
    }
    
    return 0;
}

Hexadecimal to binary (16➤2)

The conversion from hexadecimal number to binary number is realized by using switch statement and bit operation of hexadecimal number. Specifically, the program traverses each character of the input hexadecimal number, and then uses the corresponding case tag according to the value of the character to add the corresponding binary number to the output.

code show as below

#include <stdio.h>

int main() {
    
    
    char hex[17];
    int i = 0;

    // 读入16进制数
    printf("请输入16进制数:");
    scanf("%s", hex);

    printf("对应的2进制数为:");
    while (hex[i]) {
    
    
        switch (hex[i]) {
    
    
            case '0':
                printf("0000");
                break;
            case '1':
                printf("0001");
                break;
            case '2':
                printf("0010");
                break;
            case '3':
                printf("0011");
                break;
            case '4':
                printf("0100");
                break;
            case '5':
                printf("0101");
                break;
            case '6':
                printf("0110");
                break;
            case '7':
                printf("0111");
                break;
            case '8':
                printf("1000");
                break;
            case '9':
                printf("1001");
                break;
            case 'A':
            case 'a':
                printf("1010");
                break;
            case 'B':
            case 'b':
                printf("1011");
                break;
            case 'C':
            case 'c':
                printf("1100");
                break;
            case 'D':
            case 'd':
                printf("1101");
                break;
            case 'E':
            case 'e':
                printf("1110");
                break;
            case 'F':
            case 'f':
                printf("1111");
                break;
            default:
                printf("\n错误:无效的16进制数!\n");
                return 0;
        }
        i++;
    }

    return 0;
}

After running the program, enter the hexadecimal number to be converted, and the program will output the corresponding binary number. Note that the program can only process hexadecimal numbers with uppercase or lowercase letters. If the input string contains other characters, the program will prompt an invalid hexadecimal number.

Octal to binary (8➤2)

1. First, get an octal number from the user.
2. In the while loop, we simulate the binary conversion process.
3. On each iteration, store the last digit of the octal number in the rem variable.
4. Then convert it to binary and add it to binary_num variable.
5. The base variable is used to calculate each digit in a binary number.
6. Finally, print out the generated binary number.

code show as below

#include <stdio.h>

int main() {
    
    
    int octal_num, binary_num = 0, base = 1, rem;
    printf("Enter an octal number: ");
    scanf("%d", &octal_num);
    while (octal_num > 0) {
    
    
        rem = octal_num % 10;
        binary_num += rem * base;
        base *= 2;
        octal_num /= 10;
    }
    printf("Binary number: %d", binary_num);
    return 0;
}

Convert to hexadecimal

Binary to hexadecimal (2➤16)

In C language, you can use the printf function and the format string control character to implement binary to hexadecimal conversion.

code show as below

#include <stdio.h>

int main()
{
    
    
    int binary = 10101110; // 二进制数
    int hex = 0; // 十六进制数
    int i = 0;
    
    while (binary != 0) {
    
    
        // 将每四位二进制数转换为一个十六进制数
        hex += (binary % 10) * (1 << i); 
        binary /= 10;
        i += 4;
    }
    
    printf("0x%x", hex); // 输出十六进制数
    
    return 0;
}

In the above code, 10101110 is an 8-bit binary number, and every four binary digits corresponds to a hexadecimal number. In the loop, the lowest four-digit binary number is taken out each time, the corresponding hexadecimal number is calculated through a shift operation, and then accumulated into the hex variable. Finally, use the %x format string control character to output a hexadecimal number. The output result is 0xae.

Octal to hexadecimal (8➤16)

In C language, you can use the sprintf() function to convert octal to hexadecimal.

code show as below

#include <stdio.h>

int main()
{
    
    
    int octal = 037;
    char hex[10];
    sprintf(hex, "%X", octal);

    printf("%o in octal is %s in hexadecimal.\n", octal, hex);

    return 0;
}

The output is: 37 in octal is 1F in hexadecimal.

Decimal to hexadecimal (10➤16)

You can use the sprintf function to convert the decimal number into a hexadecimal string, and then use the printf function to output it.

#include <stdio.h>

int main()
{
    
    
    int dec = 336;
    char hex[10];
    sprintf(hex, "%X", dec); // 将十进制数转成十六进制字符串
    printf("%s\n", hex); // 输出十六进制数
    return 0;
}

Note: The first parameter of the sprintf function is a character array, not a pointer, because it stores the converted string in the array. When using the sprintf function, you should ensure that the target character array is large enough to accommodate the converted string. In this example, the size of the target character array hex is 10, which is enough to store the hexadecimal representation of any 32-bit integer.

Convert to octal

Binary to octal (2➤8)

code show as below

#include <stdio.h>

int main() {
    
    
    long long binaryNumber;
    int octalNumber = 0, decimalNumber = 0, i = 0;

    printf("输入一个二进制数: ");
    scanf("%lld", &binaryNumber);

    // 将二进制转换为十进制
    while (binaryNumber != 0) {
    
    
        decimalNumber += (binaryNumber % 10) * pow(2, i);
        ++i;
        binaryNumber /= 10;
    }

    i = 1;

    // 将十进制转换为八进制
    while (decimalNumber != 0) {
    
    
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }

    printf("转换为八进制数为: %d", octalNumber);

    return 0;
}

In this program, we have used two while loops: one to convert a binary number to a decimal number and another to convert a decimal number to an octal number. In the first while loop, we convert a binary number to a decimal number by multiplying the number in each bit with a power of 2. In the second while loop, we convert the decimal number to octal by calculating the product of the number in each bit and the power of 8. Finally, we use the printf function to output the result converted to an octal number.

Decimal to octal (10➤8)

code show as below

#include <stdio.h>

void DecimalToOctal(int decimalNumber)
{
    
    
    int octalNumber = 0, i = 1;
  
    // 从十进制数开始迭代
    while (decimalNumber != 0)
    {
    
    
        octalNumber += (decimalNumber % 8) * i;
        decimalNumber /= 8;
        i *= 10;
    }
  
    printf("转换后的八进制数为: %d", octalNumber);
}

int main()
{
    
    
    int decimalNumber;
  
    printf("请输入一个十进制数: ");
    scanf("%d", &decimalNumber);
  
    DecimalToOctal(decimalNumber);
  
    return 0;
}

This program takes a decimal number as input, converts it to an octal number using a while loop, and finally prints it out. The decimal number entered by the user can be read from the console through the scanf function.

Hexadecimal to octal (16➤8)

code show as below

#include <stdio.h>

int main()
{
    
    
    char hex_num[10], oct_num[10];
    int i, j, k, digit;
    long int dec_num = 0, octal_num = 0;

    printf("Enter a hexadecimal number: ");
    scanf("%s", hex_num);

    // Converting hexadecimal to decimal
    for(i = 0; hex_num[i] != '\0'; i++)
    {
    
    
        if(hex_num[i] >= '0' && hex_num[i] <= '9')
            digit = hex_num[i] - '0';
        else if(hex_num[i] >= 'A' && hex_num[i] <= 'F')
            digit = hex_num[i] - 'A' + 10;
        else if(hex_num[i] >= 'a' && hex_num[i] <= 'f')
            digit = hex_num[i] - 'a' + 10;

        dec_num = 16 * dec_num + digit;
    }

    // Converting decimal to octal
    for(j = 0; dec_num != 0; j++)
    {
    
    
        oct_num[j] = dec_num % 8 + '0';
        dec_num /= 8;
    }

    // Reversing the octal number
    for(k = j - 1; k >= 0; k--)
    {
    
    
        octal_num = 10 * octal_num + (oct_num[k] - '0');
    }

    printf("The octal equivalent of %s is %ld.\n", hex_num, octal_num);

    return 0;
}

The program first receives a hexadecimal number from the user, converts it to an integer (decimal), then converts it to an octal number, and outputs the result. The program uses a loop to calculate the decimal value of a hexadecimal number, and another loop to calculate the octal value of that decimal number. Finally, the program reverses the octal number and prints the result.

For example:

  • Monday to Friday 7pm - 9pm
  • Saturday 9am-11am
  • Sunday 3pm-6pm

Convert to decimal

Binary to decimal (2➤10)

You can use the strtol() function in C language to convert a binary string to decimal

long strtol(const char *nptr, char **endptr, int base);

Among them, nptr represents the string to be converted, endptr represents the pointer position after the conversion is completed, and base represents the base number of the converted number, usually 2, 8, 10 or 16.

code show as below

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

int main()
{
    
    
    char binary[] = "10101";
    char *endptr;
    long decimal = strtol(binary, &endptr, 2);
    printf("Binary: %s, Decimal: %ld\n", binary, decimal);
    return 0;
}

Octal to decimal (8➤10)

  • The octal variable stores the entered octal number.
  • The decimal variable stores the converted decimal number,
  • The i variable is used to calculate the corresponding power number, and the pow() function is used to calculate the power value.
  • Then in the while loop, the method of multiplying each digit by the corresponding power is used for conversion.
  • Finally output the result.

code show as below

#include <stdio.h>
#include <math.h>

int main() {
    
    
    int octal, decimal = 0, i = 0;

    printf("请输入一个八进制数:");
    scanf("%o", &octal);

    while (octal != 0) {
    
    
        decimal += (octal % 10) * pow(8, i);
        ++i;
        octal /= 10;
    }

    printf("八进制数 %o 转换为十进制数为 %d", octal, decimal);

    return 0;
}

Hexadecimal to decimal (16➤10)

You can use the strtol function in C language to convert a hexadecimal string to a decimal number.

long int strtol(const char *str, char **endptr, int base);

Among them, the first parameter str is the string that needs to be converted; the second parameter endptr is a pointer to a character pointer, used to store the unprocessed part after conversion; the third parameter base is the numerical base after conversion. Generally, 16 is used to represent hexadecimal.
code show as below

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

int main() {
    
    
    char hex[] = "1A"; // 十六进制字符串
    long int dec = strtol(hex, NULL, 16); // 转换为十进制数
    printf("%ld\n", dec); // 输出十进制数
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_43798715/article/details/131412431