【问题标题】:How can i convert a uint32_t to a char* type如何将 uint32_t 转换为 char* 类型
【发布时间】:2013-11-26 16:19:23
【问题描述】:

您好,我正在使用带有 adafruit shield 的 Arduino UNO 来显示分数值,但用于显示分数的函数只接受 char* 值,并且分数本身最多可以占用 6 位数字(000,000 到 999,999)。我试过使用 sprint() 但我没有运气,因为屏幕会像疯了一样闪烁。我认为问题在于 chars 只包含一定数量的字节,这些字节不能容纳 32 位 int,但我认为它们是解决这个问题的一种方法。绘制文本是屏蔽用于在屏幕上绘制内容的函数,输入为 char*、颜色代码、大小、x 像素、y 像素。如果有人可以帮我在这两种类型之间进行转换,请告诉我。如果他们是对我也有帮助的替代品。

我的代码:

char* textToWrite;
uint32_t currentScore = 0;
uint32_t highScore = 0;
highScore = currentScore;
sprintf(textToWrite,"%d.%d.%d.%d\0", currentScore);//sprint f not working properly right now
drawText(textToWrite, ST7735_WHITE, 1, 100, 10);

我也尝试过使用:

sprintf(textToWrite,"%u", currentScore);

【问题讨论】:

  • 确实在调用sprintf之前为textToWrite分配空间?
  • 除此之外,您可能还想了解按位运算符,例如右移>> 和按位和&
  • 而且您不必添加终止符,sprintf 会为您完成。
  • 另外,你有 4 个%d,格式后只有 1 个参数。
  • @joachim 不,我忘记了,但也许我没有正确执行此操作:realloc(textToWrite, sizeof(uint32_t));

标签: c++ c char arduino uint32-t


【解决方案1】:
char textToWrite[ 16 ];
uint32_t currentScore = 42;
// as per comment from LS_dev, platform is int 16bits
sprintf(textToWrite,"%lu", currentScore);

【讨论】:

  • Argh 如此接近,如果分数确实达到 999,999,那么屏幕会打印出 16,959
  • Arduino int 是 16 位的。要打印 32 位整数,必须使用 %lu
  • @LS_dev 好的,这在我使用 %lu 时有效,谢谢 LS_dev 和 manuell
  • @manuell 因为您在 32 位架构中使用代码。
  • 不幸的是,我的声誉太低,无法投票,所以请原谅我。 @LS_dev 是的,我忘记了 arduino 是 16 位的,有些东西会受此影响。
猜你喜欢
  • 2020-11-10
  • 2019-01-31
  • 2018-04-30
  • 2012-05-25
  • 1970-01-01
  • 1970-01-01
  • 2017-05-30
  • 1970-01-01
  • 2015-05-14
相关资源
最近更新 更多