Bit Manipulation with C++20

Contents[Show]

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.

TimelineCpp20CoreLanguage2std::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.

sourceLocation

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.

 

bitInterface5

 

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:

bit2

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;
    
}

 

bitFloorCeil

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, lennonli, Pramod Tikare Muralidhara, Peter Ware, and Tobi Heideman.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, and Richard Sargeant.

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

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++,

RainerGrimmSmall

 

Comments   

0 #1 Joshua Green 2020-12-07 11:49
Your description of std::bit_ceil looks wrong -- it should be "Finds the smallest integral power of 2 greater than or equal to the given value."
Quote
+1 #2 Rainer Grimm 2020-12-07 16:54
Quoting Joshua Green:
Your description of std::bit_ceil looks wrong -- it should be "Finds the smallest integral power of 2 greater than or equal to the given value."

Thanks, I fix it.
Quote
0 #3 Stephen Steel 2020-12-08 20:42
The definition for std::countr_one() in the table is wrong - it's a copy of the definition for std::countl_one().
Quote
0 #4 Rainer Grimm 2020-12-09 18:55
Quoting Stephen Steel:
The definition for std::countr_one() in the table is wrong - it's a copy of the definition for std::countl_one().

Thanks, I fix it.
Quote

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 4935

Yesterday 8489

Week 21950

Month 21950

All 5809626

Currently are 181 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments