tags:

views:

59

answers:

4

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 !!!

A: 

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?

Amigable Clark Kant
Please provide a reason for your answer.
leppie
can you give me an example
Your example is the same as the OP's...
leppie
i use this in for a microcontroller so i send like this USART_transmit(Str[i]); in a for but it is always 00 00
:( i tried but there is no error ret not < 0
+2  A: 

In most cases, %llu should do the trick. But you might have to use %I64u on some Windows platforms.

Frédéric Hamidi
OP probably is not using a Windows platform... with USART_transmit('x'); Probably a PIC or Atmega platform.
Amigable Clark Kant
+1  A: 

%lld is for signed long long, use %llu instead.

Georg Fritzsche
A: 

can you give an example