Is it possible to get final / absolute size types in C / C ++?
I am hiding some documentation and it looks like the spec only needs "int" or "long" or whatever to hold "at least some range of values" (often corresponding to the maximum range provided by n bytes).
Anyway, is there a sane way to request an integer of exactly n bits / bytes? I don't even need a way to specify an arbitrary length or anything weird, I just want a type with ultimately 2 bytes or ultimately 4 bytes. for example "int32" or something like that.
Currently, the way I am doing this is by having a char array of length n and then casting it to an int * and dereferencing it.
(My reasoning for this to be related to reading / writing files directly from structs, and I admit that with this I have to worry about packing and instantiating the structure and the like, but that's another problem ...)
Also, "compatibility" with such super-limited embedded systems is not a big concern.
Thank!
The C ++ 11 standard defines integer types of a specific size if available in the target architecture.
#include <cstdint>
std::int8_t c; // 8-bit unsigned integer
std::int16_t s; // 16-bit unsigned integer
std::int32_t i; // 32-bit unsigned integer
std::int64_t l; // 64-bit unsigned integer
and the corresponding unsigned types with
std::uint8_t uc; // 8-bit unsigned integer
std::uint16_t us; // 16-bit unsigned integer
std::uint32_t ui; // 32-bit unsigned integer
std::uint64_t ul; // 64-bit unsigned integer
As noted in the comments, these types are also available in C from the header stdint.h
without the namespace prefix std::
:
#include <stdint.h>
uint32_t ui;
In addition to types of a specific size, these header files also define types
- which are at least n bits wide, but can be larger, for example.
int_least16_t
with at least 16 bits - which provide the fastest implementation of integers with at least n bits, but can be more, for example.
std::int_fast32_t
with at least 32 bits.
Printed in <cstdint>
, for example int32_t
, will either be exactly that number of bits [32 in this example], or does not exist if the architecture does not support these size values. There are also types int_fast32_t
that are guaranteed to contain a 32-bit value, but there may be more types int_fast32_t
that have a similar guarantee.
In the current C ++ standard , widths are fixed integer types , for example std::int16_t
std::uint16_t
, where 16
means font size in bits.
You can use the types from <stdint.h>
, but you cannot be sure that there is exactly the type you want.
If your architecture has a precise 32-bit types, it is very likely you can use int16_t
, uint16_t
, int32_t
and uint32_t
, if not, the types int_fast32_t
and uint_fast32_t
and int_least32_t
and uint_least32_t
etc. always available.