Convert usigned integer( uint16_t) to string. Standard itoa base 10 is giving negative values

10,630

Use sprintf with %u format for unsigned int:

uint16_t i = 33000;
sprintf(str, "%u", i);
Share:
10,630
user3278790
Author by

user3278790

Updated on June 05, 2022

Comments

  • user3278790
    user3278790 about 2 years

    I need to convert uint16_t value to a string. I want the string to be a decimal respresentation of the number.

    Example: uint16_t i=256 string: 256

    I tried with itoa(i,string, 10) but when i value increases starts printing negative values.
    I send the string via the Serial Port.(UART)
    It is there some alternative?

  • sameerkn
    sameerkn over 7 years
    use snprintf(str, sizeof(str), "%d", i); even though buffer overflow chance are less.
  • Sergei Bubenshchikov
    Sergei Bubenshchikov over 7 years
    @sameerkn, please share link to a library, where you found snprintf function with presented prototype
  • user3278790
    user3278790 over 7 years
    I'm not sure, but in muy case is for firmware, I want to send the string by the Serial port, snprintf I guess it doesn't work in this case....
  • phuclv
    phuclv over 3 years
    no, the correct format specifier for uint16_t is PRIu16: printf("%" PRIu16 "\n", i);