Method for Converting Decimal to Octal and Hexadecimal in C Language

Through the program, we can quickly calculate the representation of a decimal number in other bases.

This article provides C language code for converting decimal to octal and hexadecimal.C language code.

SinceC language conversion to binary is relatively complex, we will write about it at another time.

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>
int main() {    int a;    int *ipointer1;    printf("Please enter a decimal number:\n");    scanf("%d",&a);    ipointer1 = &a;    printf("%d in octal is:%o\n", a, (*ipointer1));    printf("%d in hexadecimal is:%x\n", a, (*ipointer1));    return 0;}

Output result:

Please enter a decimal number:1010 in octal is:1210 in hexadecimal is:a

Since the above code comes from an example explaining pointers, the code appears as follows:

int a; int *ipointer1; ipointer1=&a;

It can also be expressed as (int a; int *ipointer1=&a;)

This example explains the usage of pointers, especially their function.

However, in the program for converting decimal to octal and hexadecimal, pointers seem unnecessary; it can actually be simpler and more concise.

Here is the program without pointers:

(The results displayed by the two programs are the same, but the learning outcomes during the writing process are different.)

#define _CRT_SECURE_NO_WARNINGS#include <stdio.h>int main() {    int a;    printf("Please enter a decimal number:\n");    scanf("%d",&a);
    printf("%d in octal is:%o\n", a, a);    printf("%d in hexadecimal is:%x\n", a, a);
    return 0;}

Output result:

Please enter a decimal number:1616 in octal is:2016 in hexadecimal is:10

Leave a Comment