How can you get a custom-sized integer data type? Is there any other answer than using <stdint.h>
types like uint16_t
and uint32_t
and are these types platform-independent?
The answer is mostly No. <stdint.h>
provides integers of specific sizes available on a given platform, but there's no standard way to get, say, a 20-bit integer but you can specify arbitrary size smaller than those provided by <stdint.h>
by using bitfields. The following provides a 20-bit unsigned int that works as you would expect it to, though the interface is a little clunky.
struct uint20_s {
unsigned int val : 20;
};
Broadly speaking it is non-trivial to implement integer semantics for word-sizes larger than those supported by the underlying hardware. There is an entire class of libraries dedicated to working with arbitrary precision numerics.