Sunday, July 12, 2009

How can I convert DEC to HEX in C?

I know it can be done without much or any code by just overloading a certain operator in C++. Which and How?

How can I convert DEC to HEX in C?
use %26lt;iostream.h%26gt;





Overload: cout





cout%26lt;%26lt;hex%26lt;%26lt;123;





Get the hex of the number!
Reply:makeing a few assumptios :-





1. your talking C and not C++


2. you realize that your not realy converting more changing the way it displayed.





int aNum = 77;





printf( "%x", aNum );








the %x is what prints it in Hex, check out printf docs


for zero fill etc
Reply:void main()


{


int i,temp,count=0;


char hex[10];


char hex_symbols[6]={'A','B','C','D','E','F'}...


printf("Please enter a DEC number:");


scanf("%d",%26amp;i);


while(i!=0)


{





temp=i%16;


if(i%26gt;9)


{


hex[count]=hex_symbols[i%10];


}


else


{


hex[count]=i + '0';


}


i/=16;


count++;


}


}


//The variable hex will contain the hex value...
Reply:/* you can be more robust and ask for input


* i call it convert.c


*/





#include %26lt;stdio.h%26gt;





main()


{


int n; char y[5];


printf("This program converts decimal numbers to hexadecimal\n\n");





while(1) {





printf("\nEnter decimal number: ");


scanf("%d",%26amp;n);


printf("\nNumber entered is %26lt;%d%26gt; decimal and %26lt;%x%26gt; hexa",n,n);








}





}
Reply:printf( "%x", Num );


No comments:

Post a Comment