2

I need to store an array of items, where each item is 32 bits in length. So currently I'm using an array of long. However I'm compiling on another machine now where a long is 64 bits. This creates problems when it comes to signed numbers. (i.e. printing the same number on both machines, one will be negative (32-bit) and the other will be positive (64-bit).

So the plan is to switch to int32_t, the problem is that when using format strings to print the numbers out, the specifiers need to different as on the 32-bit machine int32_t is defined as a long and on the 64-bit machine it's defined as an int.

What is the best way to make sure that it will be 32-bits on whatever machine it's compiled on, and that the number can be printed? It seems like this is a lot of hassle and that there should be a simpler/easier way to have an array of items 32-bits in length.

Jonathan.
  • 53,997
  • 54
  • 186
  • 290

2 Answers2

3

The correct way of doing it is to

#include <inttypes.h>

and then use one of the format specifier macros:

void show(int32_t the_integer) {
  printf("The 32-value is %" PRId32 " in decimal.\n", the_integer);
}

See http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/inttypes.h.html

rici
  • 234,347
  • 28
  • 237
  • 341
2

There are macros defined in <inttypes.h> that help with exactly this problem. You use

"%" PRId32

as your print format specifier, and all will be well.

Floris
  • 45,857
  • 6
  • 70
  • 122