Hi! I try to convert unsigned long long to string like this
unsigned long long Data = 12;
char Str[20];
sprintf(Str, "%lld",Data);
when i want to see but i always see 00
Str[0],Str[1]....;
whats the wrong !!!
Hi! I try to convert unsigned long long to string like this
unsigned long long Data = 12;
char Str[20];
sprintf(Str, "%lld",Data);
when i want to see but i always see 00
Str[0],Str[1]....;
whats the wrong !!!
You should use another function, called snprintf(). This will protect against buffer overruns of the string. In this case, 20 characters is not quite enough for what an unsigned integer might hold. I would recommend to increase to 23 characters or so. Then you are safe even without snprintf().
But either way, your string str
must be the first argument, then the format string, last the long long variable.
Like so:
sprintf(Str, "%lld", Data);
I honestly can not see the problem here. Are you sure you print the string correctly?
This should work. If sprintf() returns a negative value, it means it encountered a problem.
#include <stdio.h>
int main()
{
char Str[20];
unsigned long long Data = 12;
int ret;
ret = sprintf(Str, "%llu",Data);
if (ret < 0) {
printf("Error converting to string.\n");
/* USART_transmit('X'); To indicate error in your case. */
}
printf("Str: '%s'\n", Str);
return 0;
}
It may also be that your sprintf() implementation is not fully standards compliant, which I could easily imagine if you are using some kind of embedded C library.
In that case, you may have to convert your unsigned long long in two steps. Try something like this:
unsigned int low = (sizeof (int) * 8) & Data;
unsigned int high = Data >> (sizeof (int) * 8);
Also, how large is a long long on your platform and how long is an integer? What CPU are you coding for and with which compiler and libc?
If you don't know, you can find out how large a long long is like this:
if (sizeof (long long) == 8) {
USART_transmit('8');
}
if (sizeof (long long) == 4) {
USART_transmit('4');
}
if (sizeof (long long) == 2) {
USART_transmit('2');
}
Also, are you really sure you need a long long? Maybe an int is enough?
In most cases, %llu
should do the trick. But you might have to use %I64u
on some Windows platforms.