3

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?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
user3278790
  • 75
  • 1
  • 3
  • 9

2 Answers2

2

Use sprintf with %u format for unsigned int:

uint16_t i = 33000;
sprintf(str, "%u", i);
zmechanic
  • 1,842
  • 21
  • 27
  • 1
    no, the correct format specifier for `uint16_t` is `PRIu16`: `printf("%" PRIu16 "\n", i);` – phuclv Dec 14 '20 at 03:28
0

You can try to use sprintf() for common "to string" conversions. For example:

#include <stdio.h>
#include <math.h>

int main() {
   uint16_t i = 256;
   char str[80];

   int str_len = sprintf(str, "%d", i);

   return(0);
}

For more info look at this article.

Sergei Bubenshchikov
  • 5,275
  • 3
  • 33
  • 60