Fixed width integers are integer data types with fixed data size across different system architectures. For example, if an integer is of fixed width 16 bits, it will be 16 bits on all the systems.
Fixed width integers contains width and suffixed with t. For example, int8_t, int16_t etc. To use these integers, we need to include cstdint header file.
For example,
#include <iostream>
#include <cstdint>
int main(int argc, char const *argv[])
{
std::int16_t num2{32767};
std::cout << num2 << std::endl;
return 0;
}There are some more fixed width integers available:
| Name | Fixed size |
|---|---|
std::int8_t | 1 byte signed |
std::int16_t | 2 bytes signed |
std::int32_t | 4 bytes signed |
std::int64_t | 8 bytes signed |
std::uint8_t | 1 byte unsigned |
std::uint16_t | 2 bytes unsigned |
std::uint32_t | 4 bytes unsigned |
std::uint64_t | 8 bytes unsigned |
Why we need Fixed width integers?
C++ only guarantees that integer data type will have a minimum size but not limits on the maximum size. Maximum size depends on the system architectures and their compilers.
For example, int data type can have 16 bits minimum size but usually have 32 bits and 64 bits on modern systems. As a result, program designed to be portable can have issues with integer ranges. For example, if a variable of int in one system is 32 bits will have bigger range than the one on another system with int 16 bits.
Different computer architectures perform well on certain size of data size. For example, one computer CPU can work fast with 32 bits int while another with 64 bits int. So, language standards kept the size of integer open so that compilers use the size that performs best with the targeting different architecture.
How fixed width integer works?
Fixed width integers are just alias to the existing integral types with the desired size. For example, if a system has int with 32 bits size then int32_t will be alias of int.
8-bits fixed with integrals are alias for char because it is 8 bit integral. So, int8_t is an alias to signed char and uint8_t to unsigned char.
So, if we print value = 65 of type int8_t, we would see character A.