• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1045
  • Last Modified:

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!
0
nscappdev
Asked:
nscappdev
  • 2
  • 2
  • 2
1 Solution
 
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
 
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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
 
DanRollinsCommented:
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
 
nscappdevAuthor Commented:
DanRollins,

Your solution worked! Thanks!
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now