简体   繁体   中英

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. This PIN is a string of length 5 (eg "1234\0"). The real PIN is obtained after some calculations, by converting a uint64_t to string and extracting the first 4 characters:

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. I've tried solutions like using the PRIu64 modifier from the inttypes.h library, but it still doesn't work.

I don't mind to change this function if there is a way to avoid the use of sprintf .

Thanks!

run this on a STM32 chip and the sprintf function doesn't work properly

You are using standard C library implementation (most probably newlib in it's "nano") version that does not support long long printf format specifiers.

Either:

  • do not use long long format specifier and find other way
  • provide your own library for printing long long numbers
  • use a C standard library that supports long long printing
    • ie. use full newlib version, ie. remove -specs=nano.specs or -lnano from your compiler command line

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.
  • prefer snprintf to protect against buffer overflows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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