How to print in decimal instead of hex using printf with esp-idf

264 views Asked by At

I am trying to print CAN bus messages that are received by an ESP32-S3 using the esp-idf framework. The provided example code for TWAI/CAN bus from the framework is shown below:

printf("ID is %d\n", message.identifier);
if (!(message.rtr)) {
    for (int i = 0; i < message.data_length_code; i++) {
        printf("Data byte %d = %d\n", i, message.data[i]);
    }
}

If I send a CAN message with ID 123, it displays as 291, which is the same value but in hex. How can I specify the output format of the printf function?

I have googled and tried many solutions but I cannot seem to print the values in decimal.

Here is a link to the TWAI API reference for esp-idf

I have tried the following:

    printf("%" PRIu32 "\n",a);
    printf("%lu\n", (unsigned long)a

But none seem to work.

1

There are 1 answers

0
BitBank On

val = 291 decimal:

printf("%d", val);

Outputs --> 291

printf("0x%x", val);

Outputs --> 0x123

The %x formatting variable tells printf to display the value as Hexadecimal. You can also specify the number of digits to display.

printf("0x%04x", val);

Outputs --> 0x0123