简体   繁体   English

如何在十六进制的uint32_t上执行sprintf并将其存储到字符串中?

[英]How to do a sprintf on a uint32_t hexidecimal to and store it into a string?

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. 因此,我需要对uint32_t十六进制执行sprintf来将其存储到字符串中。 But I keep getting an error on the %08X . 但是我在%08X上一直遇到错误。 So what should I use instead? 那我该怎么用呢? I have tried using %ll , %lu but the warning is still there. 我尝试使用%ll%lu但警告仍然存在。

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? 谁能帮我这个?

You should be getting an error because str_cycles is shown as volatile char str_cycles; 您应该得到一个错误,因为str_cycles显示为volatile char str_cycles; (a single character). (一个字符)。

You should be using <inttypes.h> and: 您应该使用<inttypes.h>和:

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() . 通常, snprintf()应该比sprintf()更可取,但是如果您分配了足够的空间,那么使用sprintf()完全可以。

I'm not convinced about the volatile qualifier either; 我也不相信volatile限定词。 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.) (这个答案第一省略volatilestr_cycles ,然后加入它,现在已经再次省略了。)

Use fixed width print specifiers. 使用固定宽度的打印说明符。

#include <inttypes.h>
char buf[9];
sprintf(buf, "%08" PRIX32,total_cycles);

Cast to an int or unsigned first. 首先转换为intunsigned This is the type expected by %X : 这是%X期望的类型:

sprintf(str_cycles, "%08X", (unsigned) total_cycles);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM