Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom int size other than using <stdint.h>

Tags:

c

int

size

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?

like image 469
tomashauser Avatar asked Dec 11 '22 01:12

tomashauser


2 Answers

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.

like image 198
nickelpro Avatar answered Dec 12 '22 13:12

nickelpro


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.

like image 28
Eric Postpischil Avatar answered Dec 12 '22 15:12

Eric Postpischil