Convert Large number to hex in C

sprintf(myHex, "%x", myInt); works for small numbers but is there a way to convert large numbers (larger than 2^32) to hex string or number in C?

Thank you!
nscappdevAsked:
Who is Participating?
 
DanRollinsConnect With a Mentor Commented:
Attached code seems to work, at least for positive values.
#include <stdio.h>
#include <math.h>
 
int main (int argc, char *argv[])
{
	double d= 0x123456789abcde;
 
	unsigned long ulLo= long( fmod(d,0x100000000) );
	unsigned long ulHi= long(    d / 0x100000000  );
 
	printf("%08x\r\n", ulLo);
	printf("%08x\r\n", ulHi);
	printf("%08x%08x\r\n", ulHi, ulLo);
 
   return(0);
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
Try the code below...

Please note this is Windows specific, the C standard only specifics %x and %X for formatting hex numbers.
	unsigned long long ull = 0xFFFFFFFFFFFFFFFF;
	printf("%I64x", ull);

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
Strictly speaking, you might need to add ULL as a suffix to the number to tell the compiler it's a 64bit number and not an int type.

unsigned long long ull = 0xFFFFFFFFFFFFFFFFULL;
0
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

 
DanRollinsCommented:
It's also pretty easy to break a 64-bit value into two 32-bit values, and then output the combined series of  16 hex digits.  If you need to see code to do that, let me know.
0
 
nscappdevAuthor Commented:
Thanks for the answers. I wish it could be that straightforward.  I'm using Informix ESQL/C. So unsigned long long and format specifier %I64x doesn't work for me. I'm using double to hold the large number. I am looking for a solution that can covert that large double number to hex

Thank you

0
 
nscappdevAuthor Commented:
DanRollins,

Your solution worked! Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.