Needful Software

Boost.Endian

Introduction

As the name implies the Boost.Endian[1] library provides functions to convert data between its little endian and big endian representations.

Conversion Example

Our first example will show how to convert an integer from its native representation to its little endian and big endian representations using the boost::endian::native_to_little and boost::endian::native_to_big functions. The full example is available from our GitHub repository: BoostTutorials/Endian/Conversion1

 File: main.cpp
#include <boost/endian/conversion.hpp>
#include <iostream>

int main(int argc, char* argv[])
{
    unsigned int nativeInt = 0x12345678;
    unsigned int littleEndianInt = boost::endian::native_to_little(nativeInt);
    unsigned int bigEndianInt = boost::endian::native_to_big(nativeInt);

    std::cout << "Native endianness: 0x" << std::hex << nativeInt << std::endl;
    std::cout << "Little endian:     0x" << std::hex << littleEndianInt << std::endl;
    std::cout << "Big endian:        0x" << std::hex << bigEndianInt << std::endl;

    return 0;
}

On a little endian architecture the program will generate the following output.

 Console output
Native endianness: 0x12345678
Little endian:     0x12345678
Big endian:        0x78563412
Press any key to continue . . .

References

  1. Boost.Endian: official documentation (boost.org)