简体   繁体   English

uint64_t 字符串转换和前4个字符的提取

[英]uint64_t string conversion and extraction of first 4 characters

I've been handed this function that checks if a given 4 digit PIN number is correct.我收到了这个 function 来检查给定的 4 位 PIN 码是否正确。 This PIN is a string of length 5 (eg "1234\0").此 PIN 是长度为 5 的字符串(例如“1234\0”)。 The real PIN is obtained after some calculations, by converting a uint64_t to string and extracting the first 4 characters:真正的 PIN 是经过一些计算得到的,通过将 uint64_t 转换为字符串并提取前 4 个字符:

uint8_t pin_verification(uint64_t number, uint8_t *pin)
{
  uint8_t string[14];

  // ASCII string conversion
  sprintf((char *)(string), "%llu", number);

  // Pin verification
  if (memcmp(pin, string, 4))
  {
    return 0;
  }
  else
  {
    return 1;
  }
}

I've been told that it works, but I'm trying to run this on a STM32 chip and the sprintf function doesn't work properly.有人告诉我它可以工作,但我试图在 STM32 芯片上运行它,而sprintf function 不能正常工作。 I've tried solutions like using the PRIu64 modifier from the inttypes.h library, but it still doesn't work.我已经尝试过使用inttypes.h库中的PRIu64修饰符等解决方案,但它仍然不起作用。

I don't mind to change this function if there is a way to avoid the use of sprintf .如果有办法避免使用sprintf ,我不介意更改此 function 。

Thanks!谢谢!

run this on a STM32 chip and the sprintf function doesn't work properly在 STM32 芯片上运行它并且 sprintf function 不能正常工作

You are using standard C library implementation (most probably newlib in it's "nano") version that does not support long long printf format specifiers.您正在使用不支持 long long printf 格式说明符的标准 C 库实现(很可能是“nano”中的newlib )版本。

Either:任何一个:

  • do not use long long format specifier and find other way不要使用 long long 格式说明符并找到其他方式
  • provide your own library for printing long long numbers提供你自己的库来打印长长的数字
  • use a C standard library that supports long long printing使用支持长长打印的C标准库
    • ie. IE。 use full newlib version, ie.使用完整的 newlib 版本,即。 remove -specs=nano.specs or -lnano from your compiler command line从编译器命令行中删除-specs=nano.specs-lnano

Note that:注意:

  • told that it can be 14 digits long maximum then 14 byte buffer is too short to store a string with 14 digits. told that it can be 14 digits long maximum然后 14 字节缓冲区太短而无法存储 14 位的字符串。
  • prefer snprintf to protect against buffer overflows更喜欢snprintf来防止缓冲区溢出

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

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