C program to convert Decimal to Hexadecimal number system

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.

Example:
Input decimal number: (26)10
Output hexadecimal number: (1A)16

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. 0 1 2 3 4 5 6 7 8 9

Hexadecimal number system:

Hexadecimal number system is a base 16 number system. Hexadecimal number system uses 16 symbols to represent all numbers i.e. 0 1 2 3 4 5 6 7 8 9 A B C D E F

Algorithm to convert from Decimal to Hexadecimal:

Conversion 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:

/**
 * 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;
    
    /*
     * Reads decimal number from user
     */
    printf("Enter any decimal number: ");
    scanf("%lld", &decimal);
    tempDecimal = decimal;

    index = 0;
    
    /*
     * Finds the hexadecimal of decimal number
     */
    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 ;)


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
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment