![]() |
Endian Integer Types |
| Boost Home Endian Home Conversion Functions Endian Types Tutorial |
Header <boost/endian/types.hpp> provides integer-like byte-holder binary types with explicit control over byte order, value type, size, and alignment. Typedefs provide easy-to-use names for common configurations.
These types provide portable byte-holders for integer data, independent of particular computer architectures. Use cases almost always involve I/O, either via files or network connections. Although data portability is the primary motivation, these integer byte-holders may also be used to reduce memory use, file size, or network activity since they provide binary integer sizes not otherwise available.
Such integer byte-holder types are traditionally called endian types. See the Wikipedia for a full exploration of endianness, including definitions of big endian and little endian.
Boost endian integers provide the same full set of C++ assignment, arithmetic, and relational operators as C++ standard integral types, with the standard semantics.
Unary arithmetic operators are +, -, ~,
!, prefix and postfix -- and ++. Binary
arithmetic operators are +, +=, -,
-=, *, *=, /, /=,
%/ %=, &, &=, |, |=,
^, ^=, <<, <<=, >>,
>>=. Binary relational operators are ==, !=,
<, <=, >, >=.
Automatic conversion is provided to the underlying integer value type.
The endian_example.cpp program writes a binary file containing four byte big-endian and little-endian integers:
#include <iostream>
#include <cstdio>
#include <boost/endian/types.hpp>
#include <boost/static_assert.hpp>
using namespace boost::endian;
namespace
{
// This is an extract from a very widely used GIS file format. Who knows
// why a designer would mix big and little endians in the same file - but
// this is a real-world format and users wishing to write low level code
// manipulating these files have to deal with the mixed endianness.
struct header
{
big_int32_t file_code;
big_int32_t file_length;
little_int32_t version;
little_int32_t shape_type;
};
const char* filename = "test.dat";
}
int main(int, char* [])
{
BOOST_STATIC_ASSERT(sizeof(header) == 16U); // reality check
header h;
h.file_code = 0x01020304;
h.file_length = sizeof(header);
h.version = 1;
h.shape_type = 0x01020304;
// Low-level I/O such as POSIX read/write or <cstdio> fread/fwrite is sometimes
// used for binary file operations when ultimate efficiency is important.
// Such I/O is often performed in some C++ wrapper class, but to drive home the
// point that endian integers are often used in fairly low-level code that
// does bulk I/O operations, <cstdio> fopen/fwrite is used for I/O in this example.
std::FILE* fi = std::fopen(filename, "wb"); // MUST BE BINARY
if (!fi)
{
std::cout << "could not open " << filename << '\n';
return 1;
}
if (std::fwrite(&h, sizeof(header), 1, fi)!= 1)
{
std::cout << "write failure for " << filename << '\n';
return 1;
}
std::fclose(fi);
std::cout << "created file " << filename << '\n';
return 0;
}
After compiling and executing endian_example.cpp,
a hex dump of test.dat shows:
01020304 00000010 01000000 04030201
Notice that the first two 32-bit integers are big endian while the second two are little endian, even though the machine this was compiled and run on was little endian.
Requires <climits> CHAR_BIT == 8. If CHAR_BIT
is some other value, compilation will result in an #error. This
restriction is in place because the design, implementation, testing, and
documentation has only considered issues related to 8-bit bytes, and there have
been no real-world use cases presented for other sizes.
In C++03, endian does not meet the requirements for POD types
because it has constructors, private data members, and a base class. This means
that common use cases are relying on unspecified behavior in that the C++
Standard does not guarantee memory layout for non-POD types. This has not been a
problem in practice since all known C++ compilers do layout memory as if
endian were a POD type. In C++11, it is possible to specify the
default constructor as trivial, and private data members and base classes will
no longer disqualify a type from being a POD. Thus under C++11, endian
will no longer be relying on unspecified behavior.
Two scoped enums are provided:
enum class order {big, little, native};
enum class align {no, yes};
One class template is provided:
template <order Order, typename T, std::size_t n_bits, align A = align::no> class endian;
Typedefs, such as big_int32_t, provide convenient naming
conventions for common use cases:
Name Endianness Sign Sizes in bits (n) Alignment big_intn_tbigsigned 16,32,64 yesbig_uintn_tbigunsigned 16,32,64 yeslittle_intn_tlittlesigned 16,32,64 yeslittle_uintn_tlittleunsigned 16,32,64 yesbig_n_tbigsigned 8,16,24,32,40,48,56,64 nobig_un_tbigunsigned 8,16,24,32,40,48,56,64 nolittle_n_tlittlesigned 8,16,24,32,40,48,56,64 nolittle_un_tlittleunsigned 8,16,24,32,40,48,56,64 nonative_n_tnativesigned 8,16,24,32,40,48,56,64 nonative_un_tnativeunsigned 8,16,24,32,40,48,56,64 no
The unaligned types do not cause compilers to insert padding bytes in classes and structs. This is an important characteristic that can be exploited to minimize wasted space in memory, files, and network transmissions.
Warning: Code that uses aligned types is inherently non-portable because alignment requirements vary between hardware architectures and because alignment may be affected by compiler switches or pragmas. Furthermore, aligned types are only available on architectures with 16, 32, and 64-bit integer types.
Note: One-byte big-endian, little-endian, and native-endian types have identical functionality. They are provided to improve code readability and searchability.
When first exposed to endian types, programmers often fit them into a mental model
based on the <cstdint> types. Using that model, it is natural to
expect a 56-bit big-endian signed integer to be named int_big56_t
rather than big56_t.
As experience using these type grows, the realization creeps in that they are lousy arithmetic integers - they are really byte holders that for convenience support arithmetic operations - and for use in internal interfaces or anything more than trivial arithmetic computations it is far better to convert values of these endian types to traditional integer types.
That seems to lead to formation of a new mental model specific to endian byte-holder types. In that model, the endianness
is the key feature, and the integer aspect is downplayed.
Once that mental transition is made, a name like big56_t is a good
reflection of the mental model
endianAn endian is an integer byte-holder with user-specified endianness, value type, size, and alignment. The usual operations on integers are supplied.
namespace boost
{
namespace endian
{
// C++11 features emulated if not available
enum class order {big, little, native};
enum class align {no, yes};
template <order Order, typename T, std::size_t n_bits, align A = align::no>
class endian
{
public:
typedef T value_type;
// if BOOST_ENDIAN_FORCE_PODNESS is defined && C++11 POD's are not
// available then these two constructors will not be present
endian() noexcept = default;
explicit endian(T v) noexcept;
endian& operator=(T v) noexcept;
operator T() const noexcept;
const char* data() const noexcept;
// arithmetic operations; additional operators provided by value_type
value_type operator+(const endian& x) noexcept;
endian& operator+=(endian& x, value_type y) noexcept;
endian& operator-=(endian& x, value_type y) noexcept;
endian& operator*=(endian& x, value_type y) noexcept;
endian& operator/=(endian& x, value_type y) noexcept;
endian& operator%=(endian& x, value_type y) noexcept;
endian& operator&=(endian& x, value_type y) noexcept;
endian& operator|=(endian& x, value_type y) noexcept;
endian& operator^=(endian& x, value_type y) noexcept;
endian& operator<<=(endian& x, value_type y) noexcept;
endian& operator>>=(endian& x, value_type y noexcept;
value_type operator<<(const endian& x, value_type y) noexcept;
value_type operator>>(const endian& x, value_type y) noexcept;
endian& operator++(endian& x) noexcept;
endian& operator--(endian& x) noexcept;
endian operator++(endian& x, int) noexcept;
endian operator--(endian& x, int) noexcept;
};
// aligned big endian signed integer types
typedef endian<order::big, int16_t, 16, align::yes> big_int16_t;
typedef endian<order::big, int32_t, 32, align::yes> big_int32_t;
typedef endian<order::big, int64_t, 64, align::yes> big_int64_t;
// aligned big endian unsigned integer types
typedef endian<order::big, uint16_t, 16, align::yes> big_uint16_t;
typedef endian<order::big, uint32_t, 32, align::yes> big_uint32_t;
typedef endian<order::big, uint64_t, 64, align::yes> big_uint64_t;
// aligned little endian signed integer types
typedef endian<order::little, int16_t, 16, align::yes> little_int16_t;
typedef endian<order::little, int32_t, 32, align::yes> little_int32_t;
typedef endian<order::little, int64_t, 64, align::yes> little_int64_t;
// aligned little endian unsigned integer types
typedef endian<order::little, uint16_t, 16, align::yes> little_uint16_t;
typedef endian<order::little, uint32_t, 32, align::yes> little_uint32_t;
typedef endian<order::little, uint64_t, 64, align::yes> little_uint64_t;
// aligned native endian typedefs are not provided because
// <cstdint> types are superior for this use case
// unaligned big endian signed integer types
typedef endian<order::big, int_least8_t, 8> big_8_t;
typedef endian<order::big, int_least16_t, 16> big_16_t;
typedef endian<order::big, int_least32_t, 24> big_24_t;
typedef endian<order::big, int_least32_t, 32> big_32_t;
typedef endian<order::big, int_least64_t, 40> big_40_t;
typedef endian<order::big, int_least64_t, 48> big_48_t;
typedef endian<order::big, int_least64_t, 56> big_56_t;
typedef endian<order::big, int_least64_t, 64> big_64_t;
// unaligned big endian unsigned integer types
typedef endian<order::big, uint_least8_t, 8> big_u8_t;
typedef endian<order::big, uint_least16_t, 16> big_u16_t;
typedef endian<order::big, uint_least32_t, 24> big_u24_t;
typedef endian<order::big, uint_least32_t, 32> big_u32_t;
typedef endian<order::big, uint_least64_t, 40> big_u40_t;
typedef endian<order::big, uint_least64_t, 48> big_u48_t;
typedef endian<order::big, uint_least64_t, 56> big_u56_t;
typedef endian<order::big, uint_least64_t, 64> big_u64_t;
// unaligned little endian signed integer types
typedef endian<order::little, int_least8_t, 8> little_8_t;
typedef endian<order::little, int_least16_t, 16> little_16_t;
typedef endian<order::little, int_least32_t, 24> little_24_t;
typedef endian<order::little, int_least32_t, 32> little_32_t;
typedef endian<order::little, int_least64_t, 40> little_40_t;
typedef endian<order::little, int_least64_t, 48> little_48_t;
typedef endian<order::little, int_least64_t, 56> little_56_t;
typedef endian<order::little, int_least64_t, 64> little_64_t;
// unaligned little endian unsigned integer types
typedef endian<order::little, uint_least8_t, 8> little_u8_t;
typedef endian<order::little, uint_least16_t, 16> little_u16_t;
typedef endian<order::little, uint_least32_t, 24> little_u24_t;
typedef endian<order::little, uint_least32_t, 32> little_u32_t;
typedef endian<order::little, uint_least64_t, 40> little_u40_t;
typedef endian<order::little, uint_least64_t, 48> little_u48_t;
typedef endian<order::little, uint_least64_t, 56> little_u56_t;
typedef endian<order::little, uint_least64_t, 64> little_u64_t;
// unaligned native endian signed integer types
typedef endian<order::native, int_least8_t, 8> native_8_t;
typedef endian<order::native, int_least16_t, 16> native_16_t;
typedef endian<order::native, int_least32_t, 24> native_24_t;
typedef endian<order::native, int_least32_t, 32> native_32_t;
typedef endian<order::native, int_least64_t, 40> native_40_t;
typedef endian<order::native, int_least64_t, 48> native_48_t;
typedef endian<order::native, int_least64_t, 56> native_56_t;
typedef endian<order::native, int_least64_t, 64> native_64_t;
// unaligned native endian unsigned integer types
typedef endian<order::native, uint_least8_t, 8> native_u8_t;
typedef endian<order::native, uint_least16_t, 16> native_u16_t;
typedef endian<order::native, uint_least32_t, 24> native_u24_t;
typedef endian<order::native, uint_least32_t, 32> native_u32_t;
typedef endian<order::native, uint_least64_t, 40> native_u40_t;
typedef endian<order::native, uint_least64_t, 48> native_u48_t;
typedef endian<order::native, uint_least64_t, 56> native_u56_t;
typedef endian<order::native, uint_least64_t, 64> native_u64_t;
} // namespace endian
} // namespace boost
endian() = default; // C++03: endian(){}
Effects: Constructs an object of type
endian<E, T, n_bits, A>.
explicit endian(T v);
Effects: Constructs an object of type
endian<E, T, n_bits, A>.Postcondition:
x == v,wherexis the constructed object.
endian& operator=(T v);
Postcondition:
x == v,wherexis the constructed object.Returns:
*this.
operator T() const;
Returns: The current value stored in
*this, converted tovalue_type.
const char* data() const;
Returns: A pointer to the first byte of the endian binary value stored in
*this.
Other operators on endian objects are forwarded to the equivalent
operator on value_type.
Why bother with endian types? External data portability and both speed and space efficiency. Availability of additional binary integer sizes and alignments is important in some applications.
Why not just use Boost.Serialization? Serialization involves a conversion for every object involved in I/O. Endian integers require no conversion or copying. They are already in the desired format for binary I/O. Thus they can be read or written in bulk.
Why bother with binary I/O? Why not just use C++ Standard Library stream inserters and extractors? Using binary rather than character representations can be more space efficient, with a side benefit of faster I/O. CPU time is minimized because conversions to and from string are eliminated. Furthermore, binary integers are fixed size, and so fixed-size disk records are possible, easing sorting and allowing direct access. Disadvantages, such as the inability to use text utilities on the resulting files, limit usefulness to applications where the binary I/O advantages are paramount.
Do these types have any uses outside of I/O? Native endianness can be used for fine grained control over size and alignment, so may be used to save memory in applications not related to I/O.
Is there is a performance hit when doing arithmetic using these types? Yes, for sure, compared to arithmetic operations on native integer types. However, these types are usually be faster, and sometimes much faster, for I/O compared to stream inserters and extractors, or to serialization.
Are endian types POD's? Yes for C++11. No for C++03, although several macros are available to force PODness in all cases.
What are the implications endian integer types not being POD's with C++03 compilers? They can't be used in unions. Also, compilers aren't required to align or lay out storage in portable ways, although this potential problem hasn't prevented use of Boost.Endian with real compilers.
Which is better, big-endian or little-endian? Big-endian tends to be a bit more of an industry standard, but little-endian may be preferred for applications that run primarily on x86 (Intel/AMD) and other little-endian CPU's. The Wikipedia article gives more pros and cons.
What good is native endianness? It provides alignment and size guarantees not available from the built-in types. It eases generic programming.
Why bother with the aligned endian types? Aligned integer operations may be faster (20 times, in one measurement) if the endianness and alignment of the type matches the endianness and alignment requirements of the machine. On common CPU architectures, that optimization is only available for aligned types. That allows I/O of maximally efficient types on an application's primary platform, yet produces data files are portable to all platforms. The code, however, is likely to be more fragile and less portable than with the unaligned types.
These types are really just byte-holders. Why provide the arithmetic operations at all? Providing a full set of operations reduces program clutter and makes code both easier to write and to read. Consider incrementing a variable in a record. It is very convenient to write:
++record.foo;
Rather than:
int temp(record.foo);
++temp;
record.foo = temp;
Classes with similar functionality have been independently developed by several Boost programmers and used very successful in high-value, high-use applications for many years. These independently developed endian libraries often evolved from C libraries that were also widely used. Endian integers have proven widely useful across a wide range of computer architectures and applications.
Neil Mayhew writes: "I can also provide a meaningful use-case for this library: reading TrueType font files from disk and processing the contents. The data format has fixed endianness (big) and has unaligned values in various places. Using Boost.Endian simplifies and cleans the code wonderfully."
The availability of the C++11
Defaulted Functions feature is detected automatically, and will be used if
present to ensure that objects of class endian are trivial, and
thus POD's.
Boost.Endian is implemented entirely within headers, with no need to link to any Boost object libraries.
Several macros allow user control over features:
class endian to have no
constructors. The intended use is for compiling user code that must be
portable between compilers regardless of C++11
Defaulted Functions support. Use of constructors will always fail, class endian objects are POD's even though they have
constructors.Original design developed by Darin Adler based on classes developed by Mark
Borgerding. Four original class templates combined into a single endian
class template by Beman Dawes, who put the library together, provided
documentation, added the typedefs, and also added the unrolled_byte_loops
sign partial specialization to correctly extend the sign when cover integer size
differs from endian representation size.
Last revised: 22 May, 2013
© Copyright Beman Dawes, 2006-2009
Distributed under the Boost Software License, Version 1.0. See www.boost.org/ LICENSE_1_0.txt