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

18.3k Views Asked by At

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?

2

There are 2 best solutions below

3
Sergei Bubenshchikov On

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.

1
zmechanic On

Use sprintf with %u format for unsigned int:

uint16_t i = 33000;
sprintf(str, "%u", i);