An easy question: how do you print a long long nicely as hex?

I wanted to print a long long nicely, consistent with other lines of output. It took me a while to get working properly.

The code

printf("... %20.16llx\n",ll);
  • The x means print as hexadecimal
  • ll means treat the value as a long long
  • 20.16. The 20 is the the minimum number of characters printed. The second 16 specifies the number of characters to be output. In the past, I’ve used formatting to print numbers so they line up in a column.

Below is the formatting string, and the output

.%16.llx.    .              68.
.%16.16llx. .0000000000000068.
.%.llx. .68.
.%llx. .68.

My final formatting string is

printf("Serial Number in hex:%llx\n",ll);

Serial Number in hex:68

It is another of the “it is always easy when you know the answer”.

My original problem was “how do you nicely print a variable length string”.

I solved it

char longChar[8];
char * pData; // points to the data
int lData = ... ; // length of the data
memset(&longChar[0],0,sizeof(longChar); // clear it to 0
memcpy(&longChar[8-lData],
pdata,
lData
);
long long ll;
memcpy(&ll,&longChar,8);
printf("Serial number Hex %llx\n",ll);

There may be better ways of doing it (please suggest a better way of doing it), but it works.

Leave a comment