Do you know how to convert uint32_t to string?
Thank you very much,
Printable View
Do you know how to convert uint32_t to string?
Thank you very much,
Code:char str[10];
uint32_t num = 50;
sprintf( str, "%u", num );
Another way without sprintf would be:
Code:#include <stdint.h>
#include <stdio.h>
int main(void)
{
uint32_t y;
uint32_t x = 50;
unsigned char buf[4];
/* pack into buf string */
buf[0] = x >> 24;
buf[1] = x >> 16;
buf[2] = x >> 8;
buf[3] = x;
/* convert the string back to a uint32_t */
y = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
printf("y: %d = %d\n", y, x);
return 0;
}
The easiest way is snprintf(), but don't use the %u specifier! There's no guarantee that an unsigned int is the same thing as a uint32_t. There are a couple of methods I'd suggest to do this, each of which is ugly in its own way:
The first method converts the uint32_t to an unsigned long, which is guaranteed to be large enough to hold any possible uint32_t value. The second method uses a macro to get the proper conversion specifier.Code:#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
int main(void)
{
char str[11]; /* 11 bytes: 10 for the digits, 1 for the null character */
uint32_t n = 12345;
snprintf(str, sizeof str, "%lu", (unsigned long)n); /* Method 1 */
snprintf(str, sizeof str, "%" PRIu32, n); /* Method 2 */
}
The fact that %u might work on your system is no guarantee that it will work everywhere, so please don't rely on it. The methods I showed are admittedly uglier, but they're at least portable.
That won't become a C style string tho' - it's just the binary data stored in 4 unsigned char's - a C style string has a 0-character for termination. Your method may well end up with a zero in the middle of the character array, and is by no means sure to have a zero at the end (and there is no space for a zero either).
--
Mats
Ehm, that would almost certainly print rubbish if num is correctly defined as a 32-bit number - since it will use whatever is after the number in memory to use as the other 32-bit part of the 64-bit number. Aside from that, it's specific to Windows.
As an example:
prints:Code:#include <stdio.h>
int main()
{
unsigned int x = 7;
printf("x = %I64d\n", x);
return 0;
}
Which doesn't look very much like 7 to me...Code:x = 18035564108316679
--
Mats