Game Development Reference
In-Depth Information
The
int8_t
and
uint8_t
provide integers that are 8 bits or one byte in length. The
u
version is
unsigned
and the
non-u
version is
signed
. The other types are similar but of their equivalent fixed
length. There are 16-bit versions, 32-bit versions, and 64-bit versions of integers.
Note
You should avoid using the 64-bit integers for the time being unless you explicitly need numbers that
cannot be stored within 32 bits. Most processors still operator on 32-bit integers when doing arithmetic. Even
64-bit processors that have 64-bit memory addresses for pointers still do normal arithmetic using 32-bit ints.
In addition, 64-bit values use twice as much memory as 32-bit values, which increases the RAM required to
execute your program.
The next problem that might arise is that the
char
type might not be the same on all platforms.
C++ does not supply a fixed-size
char
type, so we need to improvise a little. Every platform I have
developed games on has used 8-bit
char
types, so we're only going to account for that. We will,
however, define our own
char
type alias so that if you ever do port code to a platform with chars
larger than 8 bits then you will only have to solve the problem in a single place. Listing 26-1 shows
the code for a new header,
FixedTypes.h
.
Listing 26-1.
FixedTypes.h
#pragma once
#include <cassert>
#include <cstdint>
#include <climits>
static_assert(CHAR_BIT == 8, "Compiling on a platform with large char type!");
using char8_t = char;
using uchar8_t = unsigned char;
The
FixedTypes.h
file includes
cstdint
, which gives us access to the 8- to 64-bit fixed-width
integers. We then have a
static_assert
that ensures that the
CHAR_BIT
constant is equal to 8.
The
CHAR_BIT
constant is supplied by the
climits
header and contains the number of bits that are
used by the
char
type on your target platform. This
static_assert
will ensure that our code, which
includes the
FixedTypes
header, will not compile on platforms that use a
char
with more than 8
bits. The header then defines two type aliases,
char8_t
and
uchar8_t
, which you should use when
you know you specifically need 8-bit
chars
. This isn't necessarily everywhere. Generally you will
need 8-bit
char
types when loading data that was written out using tools on another computer that
did use 8-bit character values because the length of the strings in the data will have one byte per
character rather than more. If you're not sure if you do or don't need 8 bits specifically, you're better
sticking to always using 8-bit
chars
.
The last problem solved in the
cstdint
header is for using pointers on platforms with different-sized
pointers to integers. Consider the code in Listing 26-2.