Reputation: 123
I am running a timer to calculate the efficiency of my program and I need to output it to a hyperterminal.
So, I need to do a sprintf
on a uint32_t
hexidecimal to store it into a string.
But I keep getting an error on the %08X
. So what should I use instead?
I have tried using %ll
, %lu
but the warning is still there.
volatile char str_cycles=0;
volatile uint32_t total_cycles = 0x00ffffff - current_time;
sprintf(str_cycles, "%08X",total_cycles);
Can anyone help me with this?
Upvotes: 0
Views: 2849
Reputation: 753495
You should be getting an error because str_cycles
is shown as volatile char str_cycles;
(a single character).
You should be using <inttypes.h>
and:
char str_cycles[16];
snprintf(str_cycles, sizeof(str_cycles), "%08" PRIX32, total_cycles);
Generally, snprintf()
should be preferred over sprintf()
, but if you have enough space allocated it is perfectly OK to use sprintf()
.
I'm not convinced about the volatile
qualifier either; it is your job to determine why you have that and whether it is correct and whether it matters. Generally, you do not want a volatile string; it makes using it unreliable. (This answer first omitted the volatile
on str_cycles
, then added it, and has now omitted it again.)
Upvotes: 4
Reputation: 17250
Cast to an int
or unsigned
first. This is the type expected by %X
:
sprintf(str_cycles, "%08X", (unsigned) total_cycles);
Upvotes: 0
Reputation: 153338
Use fixed width print specifiers.
#include <inttypes.h>
char buf[9];
sprintf(buf, "%08" PRIX32,total_cycles);
Upvotes: 1