Convert Decimal to Hexdecimal C++

2.5k Views Asked by At

I have this code, but it seems to print only last 4 characters of the hexadecimal conversion.

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main ()
{
int i;
char test [33];
printf ("Enter a number: ");
scanf ("%d",&i);
itoa (i,test,16);
printf ("hexadecimal: %s\n",test);
getch();
}
  • Input: 3219668508
  • Output: 3e1c
  • Expected Output: bfe83e1c

HELP?

2

There are 2 best solutions below

6
Maxim Egorushkin On

Another option is to use %x printf format specifier:

printf("hexadecimal: %x\n", i);

Avoid itoa function, it is error-prone.

6
AudioBubble On

I found a alternative to the code above, its a bit longer but works correctly.

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
unsigned long int decnum, rem, quot;
char hexdecnum[100];
int i=1, j, temp;
cout<<"Enter any decimal number : ";
cin>>decnum;
quot=decnum;
while(quot!=0)
{
    temp=quot%16;
    // to convert integer into character
    if(temp<10)
    {
        temp=temp+48;
    }
    else
    {
        temp=temp+55;
    }
    hexdecnum[i++]=temp;
    quot=quot/16;
}
cout<<"Equivalent hexadecimal value of "<<decnum<<" is : \n";
for(j=i-1; j>0; j--)
{
    cout<<hexdecnum[j];
}
getch();
}

Will need to combine the elements of the array at last part though.