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.
A little late to the party but... There is a good solution! Clang has this new feature (released on 4/24/2020), which allows you to declare custom size integers. You have to use the _ExtInt
keyword. An example:
_ExtInt(13) foo;
Look here for some more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.