Home > Back-end >  Printf unsigned hexadecimal from decimal in C
Printf unsigned hexadecimal from decimal in C

Time:08-17

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

CodePudding user response:

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;
}

CodePudding user response:

Thank you everyone for all the help. Adding more compiler warnings helped me find out about function argument mismatch and hanging "%x" to "%lx" fixed it.

typedef struct database{
    long int organization;
} database;

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