bot1131357
bot1131357

Reputation: 897

C printf specifier %lld prints characters "ld"

I am developing using gcc (-std=gnu99) for an embedded toolchain (Myriota), and I have problems with printf.

when I try the following code:

long long int time = TimeGet();
printf("\nSeconds since epoch: %lld\r\n", time);

it prints:

Seconds since epoch: ld

Using "%" PRId64 prints the same "ld".

Any ideas? I'd appreciate if you could point me to the right place.

Edit variable type corrected long long int time

Upvotes: 3

Views: 1594

Answers (3)

Keith Thompson
Keith Thompson

Reputation: 263307

Most likely, your C library, specifically its implementation of printf, doesn't support C99.

The type long long int and the %lld format were introduced by the 1999 ISO C standard (C99). Using gcc -std=c99 makes the compiler attempt to conform to C99, (or -std=cNN for later editions) but it can't make the runtime library do things that it doesn't implement. You have a mismatch between what the compiler supports and what the runtime library supports.

In C90, calling printf with %lld in the format string had undefined behavior.

Does %ld work for an argument of type long int? If the argument is in the range LONG_MIN to LONG_MAX, converting and using %ld might be a good workaround. If you need to print values less than LONG_MIN or greater than LONG_MAX, implementing a long long int to string conversion isn't horribly difficult. (And in some implementations, long int and long long int are both 64 bits, so just converting to long int and using %ld is sufficient.)

Upvotes: 6

Nicolas VERHELST
Nicolas VERHELST

Reputation: 508

#include <stdio.h>

void int64_to_string(int64_t num, char* str) {
    if (num < 0) {
        *str++ = '-';
        num = -num;
    }

    char buffer[20]; // Maximum 19 digits in int64_t
    int i = 0;
    do {
        buffer[i++] = num % 10 + '0';
        num /= 10;
    } while (num != 0);

    while (i > 0) {
        *str++ = buffer[--i];
    }
    *str = '\0';
}
int64_t num = 1234567890123456789;
char str[20]; // Maximum 19 digits in int64_t
int64_to_string(num, str);
printf("%s\n", str); // Output: "1234567890123456789"

Upvotes: 0

bot1131357
bot1131357

Reputation: 897

The Myriota SDK uses newlib-nano which does not support int64_t. I'll have to implement my own function to convert to char string, or cast to uint32_t.

Upvotes: 1

Related Questions