C program to convert Decimal to Hexadecimal number system

Write a C program to input decimal number from user and convert to Hexadecimal number system. How to convert Decimal to Hexadecimal number system in C programming. Logic to convert decimal to hexadecimal number system in C programming.

Example

Input

Input decimal number: 26

Output

Hexadecimal number: 1A

Required knowledge

Basic C programming, While loop, Array, String

Decimal number system

Decimal number system is a base 10 number system. Decimal number system uses 10 symbols to represent all number i.e. 0123456789

Hexadecimal number system

Hexadecimal number system is a base 16 number system. Hexadecimal number system uses 16 symbols to represent all numbers i.e. 0123456789ABCDEF

Algorithm to convert decimal to hexadecimal number system

Algorithm Conversion from Decimal to Hexadecimal
begin:
    read (decimal);
    hex ← NULL; rem ← 0;
    HEXVALUES[] ← 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F;
    While(decimal != 0)
        begin:
            remdecimal % 16;
            hexhex + HEXVALUES[rem];
            decimaldecimal / 16;
        end;
    Reverse(hex);
    print('Hexadecimal = ' hex);
end;

Program to convert decimal to hexadecimal number system

/**
 * C program to convert from Decimal number system to hexadecimal number system
 */

#include <stdio.h>
#include <string.h>

int main()
{
    char HEXVALUE[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    long long decimal, tempDecimal;
    char hex[65];
    int index, rem;
    
    /* Input decimal number from user */
    printf("Enter any decimal number: ");
    scanf("%lld", &decimal);
    tempDecimal = decimal;

    index = 0;
    
    /* Decimal to hexadecimal conversion */
    while(tempDecimal !=0)
    {
        rem = tempDecimal % 16;

        hex[index] = HEXVALUE[rem];

        tempDecimal /= 16;

        index++;
    }
    hex[index] = '\0';

    strrev(hex);

    printf("\nDecimal number = %lld\n", decimal);
    printf("Hexadecimal number = %s", hex);

    return 0;
}

Output

Enter any decimal number: 427
Decimal number = 427
Hexadecimal number = 1AB

Happy coding 😉