简体   繁体   中英

Printing a hex number as decimal in C

I am trying to print a hex number as decimal in C.

int main()
{
    unsigned long hex = 0xb5389e0c721a;
    printf("hex in dec: %lu", hex);
    getch();
    return 0;
}

From this, my output is 2651615770. However, when I used an online hex to dec converter and the Windows Calculator, the supposed output should be 199254774411802. What am I doing wrong?

I think Your 2651615770 output is due to overflowing. It's because a 32-bit unsigned long hex cannot hold a number this big( 0xb5389e0c721a ), so it needs bigger data type.

Try the following change-

int main()
{
    unsigned long long hex = 0xb5389e0c721a; // declare hex as unsigned long long
    printf("hex in dec: %llu", hex);
    getch();
    return 0;
}

What am I doing wrong?

You are using the unsigned long type, which is only guaranteed to be 32-bit wide and may not be able to contain the value 0xb5389e0c721a . Use unsigned long long instead, which is guaranteed to be at least 64-bit wide, and print with %llu .

The maximum value that unsigned long can contain is fixed for a given compilation platform. It is in the macro ULONG_MAX from the system header limits.h . You can also print its value for your compiler without having to include limits.h with the statement printf("%lu", (unsigned long)-1); .

The value 0xb5389e0c721a exceeds the limit of an unsigned long . Use 'unsigned long long' type instead, and print the value with a format string of "%llx" :

#include <stdio.h>

int main()
   {
   unsigned long long hex = 0xb5389e0c721a;

   printf("hex in dec: %llx\n", hex);
   return 0;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM