C++23: Bitwise Operations -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGWhile C++ is getting increasingly expressive with each new standard, we must not forget its origins. It is inherently a low-level language which operates close to the hardware level and allows operations that languages such as Javascript cannot even express.

A part of providing low-level functionalities is to be able to work on a byte or even on a bit level. In this post, we are going to see what related features C++23 brings or modifies.

C++23: Bitwise Operations

by Sandor Dargo

From the article:

constexpr std::bitset

To be fair, we already covered this earlier last year in C++23: Even more constexpr. But as I’m using this feature to demonstrate the next one, I decided to mention it again.

P2417R2 extends the constexpr interface of std::bitset. So far, only one of the constructors and operator[] was marked as constexpr. However, since std::string can be constexpr, all the internals - and therefore the full API - of std::bitset can be constexpr.

If you’re unfamiliar with std::bitset, it represents the object you pass in as a sequence of bits. You have to pass the number of bits as a non-type template argument.

#include <bitset>
#include <iostream>

int main()
{
    constexpr short i = 15;
    constexpr int numberOfBitsInInt = sizeof(i) * 8;
    std::cout << "i:" << i << ", i as binary: " << std::bitset<numberOfBitsInInt>(i) << '\n';
}
/*
i:15, i as binary: 0000000000001111
*/

It’s more capable than that, it also offers several ways to query the individual bits or set them.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.