ADVERTISEMENT
ADVERTISEMENT

C program to convert number from Decimal to Hexadecimal

In this program, we will read an integer number in Decimal and converts it into Hexadecimal Number System. This program is for Decimal to Hexadecimal Conversion in C.

The logic behind to implement this program - Get remainder using modulus operator by 16 and store it into an array (array should be character type and store A, B, C, D, E, F instead of 10, 11, 12, 13, 14, 15 respectively) then divide number by 16, repeat this process till given number is greater than 0. Because 16 is the base of Hexadecimal Number System.

For more details Learn: Computer Number System and its conversions.

Decimal to Hexadecimal Conversion using C program

/*C program to convert number from decimal to hexadecimal*/

#include <stdio.h>

int main()
{
    int number, cnt, i;
    char hex[32]; /*bcoz it contains characters A to F*/

    printf("Enter decimal number: ");
    scanf("%d", &number);

    cnt = 0; /*initialize index to zero*/
    while (number > 0) {
        switch (number % 16) {
        case 10:
            hex[cnt] = 'A';
            break;
        case 11:
            hex[cnt] = 'B';
            break;
        case 12:
            hex[cnt] = 'C';
            break;
        case 13:
            hex[cnt] = 'D';
            break;
        case 14:
            hex[cnt] = 'E';
            break;
        case 15:
            hex[cnt] = 'F';
            break;
        default:
            hex[cnt] = (number % 16) + 0x30; /*converted into char value*/
        }
        number = number / 16;
        cnt++;
    }

    /*print value in reverse order*/
    printf("Hexadecimal value is: ");
    for (i = (cnt - 1); i >= 0; i--)
        printf("%c", hex[i]);

    return 0;
}

Output:

    First Run:
    Enter decimal number: 545
    Octal value is: 221

    Second Run:
    Enter decimal number: 2806
    Hexadecimal value is: AF6

C Number System Conversion Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.