Open In App

std::endian in C++ 20

Last Updated : 18 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In C++ programming, there’s a new addition in C++20 called std::endian. It’s a helper that makes dealing with the way computers store data in memory much simpler. In this article, we will discuss the std::endian and how to use it in C++ program.

What is Endianness?

Before we look at the std::endian, let’s quickly chat about endianness. Endianness is the way computers store data that cannot be stored in a single byte like numbers. There are two types: little-endian and big-endian. Little-endian stores the least significant digit at the lower memory address and big-endian stores the most significant digits at the lower memory address.

std::endian in C++

The definition of the std::endian is C++ is:

The std::endian is an enum that stores the information about the endianess of the computer architecture.

It is defined inside <bit> header file. The std::endian enum has three members,

  1. endian::little
  2. endian::big
  3. endian::native

Here

  1. If endian::native is equal to the endian::little, then the endianness is little endian.
  2. If endian::native is equal to the endian::big, then the endianness is big endian.

Example

C++




// C++ program to illustrate the use of std::endian in C++
#include <bit>
#include <iostream>
  
using namespace std;
  
int main()
{
  
    // checking if native is little endian or big endian
    if (endian::native == endian::little) {
        cout << "This computer is little-endian!";
    }
    else if (endian::native == endian::big) {
        cout << "This computer is big-endian!";
    }
    else {
        cout << "Can't tell the endianness of this "
                "computer.";
    }
  
    return 0;
}


Output

This computer is little-endian!

This code uses std::endian to figure out if the computer is little-endian or big-endian and prints it out.

Why Endianess Matters?

The knowledge of endianess helps us to makes our code more adaptable to different computers. If our program deals with saving and reading data in a binary format (like an encrypted code), knowledge of endianess can save us from problems when our code moves to a different system.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads