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);
Author by
user3278790
Updated on June 05, 2022Comments
-
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 wheni
value increases starts printing negative values.
I send the string via the Serial Port.(UART)
It is there some alternative? -
sameerkn over 7 yearsuse
snprintf(str, sizeof(str), "%d", i);
even though buffer overflow chance are less. -
Sergei Bubenshchikov over 7 years@sameerkn, please share link to a library, where you found
snprintf
function with presented prototype -
user3278790 over 7 yearsI'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 over 3 yearsno, the correct format specifier for
uint16_t
isPRIu16
:printf("%" PRIu16 "\n", i);