C program to convert Decimal to Hexadecimal number system

Previous Program Next Program

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

Example

Input

Input decimal number: 26

Output

Hexadecimal number: 1A

Required knowledge

Basic C programming, For loop

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 from decimal to hexadecimal

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

/**
 * 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 ;)

Recommended posts

Previous Program Next Program
Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment