-1

It's been a while since coding any c, but I've got a new project I want to work on, which requires processing data files in units of fixed bit-length (32-bit). I want to make sure I can define a fixed, 32-bit type that is portable across machines.

I know CHAR_BIT in limits.h gives the number of bits in a char, and sizefof() function gives number of chars in a type (e.g. int), so I can easily multiply the two to find the number of bits in an int for example. I've read that CHAR_BIT is not always necessarily '8', and know that int type can be different sizes on different processors.

In run-time, I was thinking of using a switch statement, and typedef, to define a custom 32-bit type based on checking of CHAR_BIT and sizeof() for different int types.

I was wondering though, if this is something that could be (should be?) done with pre-processor directives instead?

  1. How would you go about doing this, to ensure code is portable and will always give a custom type of 32-bit?

  2. Out of curiosity, how would you do this for defining an arbitrary bit-length type? (presumably there is an upper bound of what you can define?)

Nabla_x
  • 21
  • 7

1 Answers1

5

#include <stdint.h> for exact width integer types!

What is wrong with int32_t and uint32_t? These are integer types without padding bits and exactly 32 value bits (uint32_t) or 31 value bits + a sign bit (int32_t). These are maximally portable, if they exist.

If however you require at least 32 bits, but the exact number of value bits is not specified, use (u)int_least32_t.