Bit Manipulation with C++20

Bit Manipulation with C++20

This is a cross-post from www.ModernesCpp.com.

This post concludes my presentation of library features in C++20. Today I write about the class std::source_location and a few functions for bit manipulation.

std::source_location

std::source_location represents information about the source code. This information includes file names, line numbers, and function names. The information is precious when you need information about the call site, such as for debugging, logging, or testing purposes. The class std::source_location is the better alternative for the predefined C++11 macros __FILE__ and __LINE__ and should, therefore, be used.

The following table shows the interface of std::source_location.

No alt text provided for this image

The call std::source_location::current() creates a new source location object src. src represents the information of the call site. Now, no C++ compiler supports std::source_location. Consequently, the following program sourceLocation.cpp is from cppreference.com/source_location.

// sourceLocation.cpp
// from cppreference.com

#include <iostream>
#include <string_view>
#include <source_location>
 
void log(std::string_view message,
         const std::source_location& location = std::source_location::current())
{
    std::cout << "info:"
              << location.file_name() << ':'
              << location.line() << ' '
              << message << '\n';
}
 
int main()
{
    log("Hello world!");  // info:main.cpp:19 Hello world!
}

The output of the program is part of its source code.

C++20 makes it quite comfortable to access or manipulate bits or bit sequences.

Bit Manipulation

Thanks to the new type std::endian, you get the endianness of a scalar type.

Endianness

  • Endianness can be big-endian or little-endian. Big-endian means that the most significant byte comes first; little-endian means that the least significant byte comes first.
  • A scalar type is either an arithmetic type, an enum, a pointer, a member pointer, or a std::nullptr_t.

The class endian provides the endianness of all scalar types:

enum class endian
{
    little = /*implementation-defined*/,
    big    = /*implementation-defined*/,
    native = /*implementation-defined*/
};
  • If all scalar types are little-endian, std::endian::native is equal to std::endian::little.
  • If all scalar types are big-endian, std::endian::native is equal to std::endian::big.

Even corner cases are supported:

  • If all scalar types have sizeof 1 and therefore endianness does not matter; the values of the enumerators std::endian::little, std::endian::big, and std::endian::native are identical.
  • If the platform uses mixed endianness, std::endian::native is neither equal to std::endian::big nor std::endian::little.

When I perform the following program getEndianness.cpp on an x86 architecture, I get the answer little-endian.

// getEndianness.cpp

#include <bit>
#include <iostream>

int main() {

    if constexpr (std::endian::native == std::endian::big) {
        std::cout << "big-endian" << '\n';
    }
    else if constexpr (std::endian::native == std::endian::little) {
        std::cout << "little-endian"  << '\n';      // little-endian
    }

}

constexpr if enables it to compile source code conditionally. This means that the compilation depends on the endianness of your architecture. If you want to know more about endianness, read the same-named Wikipedia page.

Accessing or Manipulating Bits or Bit Sequences

The following table gives you the first overview of all functions.

No alt text provided for this image

The functions except of std::bit_cast require an unsigned integer type (unsigned char, unsigned short, unsigned int, unsigned long, or unsigned long long).

The program bit.cpp shows the usage of the functions.

// bit.cpp

#include <bit>
#include <bitset>
#include <iostream>
 
int main() {
    
    std::uint8_t num= 0b00110010;
    
    std::cout << std::boolalpha;
    
    std::cout << "std::has_single_bit(0b00110010): " 
              << std::has_single_bit(num) << '\n';
    
    std::cout << "std::bit_ceil(0b00110010): " 
              << std::bitset<8>(std::bit_ceil(num)) << '\n';

    std::cout << "std::bit_floor(0b00110010): " 
              << std::bitset<8>(std::bit_floor(num)) << '\n';
    
    std::cout << "std::bit_width(5u): " << std::bit_width(5u) << '\n';
    
    std::cout << "std::rotl(0b00110010, 2): " 
              << std::bitset<8>(std::rotl(num, 2)) << '\n';

    std::cout << "std::rotr(0b00110010, 2): " 
              << std::bitset<8>(std::rotr(num, 2)) << '\n';
    
    std::cout << "std::countl_zero(0b00110010): " 
              << std::countl_zero(num) << '\n';

    std::cout << "std::countl_one(0b00110010): " 
              << std::countl_one(num) << '\n';

    std::cout << "std::countr_zero(0b00110010): " 
              << std::countr_zero(num) << '\n';

    std::cout << "std::countr_one(0b00110010): " 
              << std::countr_one(num) << '\n';

    std::cout << "std::popcount(0b00110010): " 
              << std::popcount(num) << '\n';
    
}

Here is the output of the program:

No alt text provided for this image

The next program shows the application and the output of the functions std::bit_floor, std::bit_ceil, std::bit_width, and std::bit_popcount for the numbers 2 to 7. 

// bitFloorCeil.cpp

#include <bit>
#include <bitset>
#include <iostream>
 
int main() {

    std::cout << std::endl;
    
    std::cout << std::boolalpha;
    
    for (auto i = 2u; i < 8u; ++i) {
         std::cout << "bit_floor(" << std::bitset<8>(i) << ") = " 
                   << std::bit_floor(i) << '\n';

        std::cout << "bit_ceil(" << std::bitset<8>(i) << ") = " 
                  << std::bit_ceil(i) << '\n';

        std::cout << "bit_width(" << std::bitset<8>(i) << ") = " 
                  << std::bit_width(i) << '\n';
                  
        std::cout << "bit_popcount(" << std::bitset<8>(i) << ") = " 
                  << std::popcount(i) << '\n';   
        
        std::cout << std::endl;
    }
    
    std::cout << std::endl;
    
}
No alt text provided for this image

What's next?

Additionally to coroutines, C++20 has much to offer for concurrency First, C++20 has new atomics. The new atomics exists for floating-point values and smart pointers. C++20 also enables waiting on atomics. To coordinate threads, semaphore, latches, and barriers come into play. Also, the std::thread was improved with std::jthread. The execution of a std::jthread can be interrupted and joins automatically in its destructor.

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Wolfgang Gärtner, Louis St-Amour, Stephan Roslen, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Avi Kohn, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, Sudhakar Balagurusamy, lennonli, and Pramod Tikare Muralidhara.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, and Dendi Suhubdy

 

Seminars

I'm happy to give online-seminars or face-to-face seminars world-wide. Please call me if you have any questions.

Bookable (Online)

Deutsch

English

Standard Seminars 

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++

To view or add a comment, sign in

More articles by Rainer Grimm

  • Charity run for ALS

    Tomorrow, on the 28th, there will be a charity run for ALS in Rottenburg. The course is exactly 1 km long.

    2 Comments
  • Small Safety Improvements in the C++ 26 Core Language

    Safety is an important concern in C++26. Contracts are probably the most important feature for safety.

    1 Comment
  • My ALS Journey (30/n): Cippi at the CppCon

    This week was very exciting for Cippi. She visited CppCon in Aurora, near Denver.

    2 Comments
  • Contracts: Evaluation Semantic

    After briefly presenting the details of contracts in my last article, “Contracts: A Deep Dive“, I would like to take a…

  • My ALS Journey (29/n): I feel Good

    I often receive messages asking about my health and wishing me well. I am very happy to receive these messages and just…

    5 Comments
  • Contracts: A Deep Dive

    August 25, 2025/in C++26/by Rainer GrimmI already introduced contracts in the article “Contracts in C++26”. In this…

  • My ALS Journey (28/n): Bureaucracy – The German Disease

    Today I want to write about a sad topic. Bureaucracy in the German healthcare system is becoming increasingly absurd.

    2 Comments
  • Data-Parallel Types: Algorithms

    The data-parallel types library has four special algorithms for SIMD vectors. The four special algorithms are min, max,…

  • My ALS Journey (27/n): An Emergency Call

    Firstly, I would like to say that I am doing very well and have made a full recovery from my incident. However, I would…

    8 Comments
  • Data-Parallel Types: Reduction

    In this article, I will discuss reduction and mask reduction for data-parallel types. Reduction A reduction reduces the…

Others also viewed

Explore content categories