C++23: Bitwise Operations -- Sandor Dargo
While 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 ofstd::bitset
. So far, only one of the constructors andoperator[]
was marked asconstexpr
. However, sincestd::string
can beconstexpr
, all the internals - and therefore the full API - ofstd::bitset
can beconstexpr
.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.