tags:

views:

129

answers:

2

I've just started reading C and have a question about a macro.
How can I print a 5 byte integer value (that happens to be defined in a macro)? For example:

#define MAX 0xdeadbeaf12
int main(){
printf(" 0x %2x \n", MAX);
}  

This code prints adbeaf12 but not deadbeaf12.

How do I get all the bytes printed?

+3  A: 
#define MAX 0xdeadbeaf12LL

Will tell the compiler to use the longest available integer type (which will then be cast to an appropriate type wherever MAX is used).

On most platforms, the numeric literal suffix LL will correspond to signed long long, this is 64bit (8 bytes) on a 32 bit system. C's excellent typing system and compiler warnings will take care of the rest for you.

Your printf then needs to use the ll modifier:

printf(" 0x %2llx \n", MAX);
Matt Joiner
This is all to no avail if you do not also fix the printf() format string. It says 'print an unsigned int'; if 'unsigned int' is 4 bytes, it is not going to print more. You might be lucky and get to see the low-order 4 bytes (on a little-endian machine); on a big-endian machine, you would see a different value. On both types of machine, the alignment of arguments after the 64-bit integer would be completely off - leading to problems.
Jonathan Leffler
Yes, it would be a problem. But note I used "most platforms". No platform was given, I think maybe complicating things more than than necessary (the obvious error in OP is that MAX is cast to a 4 byte integer) will only confuse the matter here.
Matt Joiner
+5  A: 

I prefer to make my assumptions about the size of a variable explicit. The following uses standard (though often unused) macros to define a 64-bit constant and print such a quantity as a hex value.

#include <stdio.h>

// Pull in UINT64_C and PRIx64 macros
#include <inttypes.h>

// Make this a 64-bit literal value
#define MAX UINT64_C(0xdeadbeaf12)

int main()
{
    // Use PRIx64 which inserts the correct printf specifier for
    // a hex format of a 64-bit value
    printf(" 0x%" PRIx64 " \n", MAX);
}
nall
+1 for UINT64_C() from §7.18.4.1 of the C99 standard (and PRIx64, which is consistent with the question, though I'd use PRIX64 for preference).
Jonathan Leffler
For the original poster's benefit, PRIx64 will print lowercase hex digits, while PRIX64 will print uppercase.
nall