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.
You can get a custom-width integer as a member in a structure by using a bit field, as in:
struct foo { int x : 13; } f;
The maximum width supported for a bit-field is depends on both the implementation and the base type (int
above) used for it.
The widths of standard types such as uint16_t
and uint32_t
are of course not implementation-dependent, but whether they are provided by an implementation is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With