Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Printf unsigned hexadecimal from decimal in C

So I’ve just started learning C this week and currently practising basic functions. There was a question that required me to print out a long int in hexadecimal, but the printout I got wasn’t the same as the sample answer. Here’s the code I wrote. Thanks heaps.

typedef struct database{
    long int organization;
} database;

int main() {
    struct database database = {-481};
    printf("%x", database.organization);
    return 0;
}

expected result: fffffffffffffe1f

result recieved: fffffe1f

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

long int is non-portable and can have different sizes. Instead use portable types from stdint.h and in case of printf print them using inttypes.h:

#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>

typedef struct database{
    uint64_t organization;
} database;

int main() {
    struct database database = {-481};
    printf("%"PRIX64, database.organization);
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading