Skip to content
DryPerspective edited this page Sep 21, 2023 · 1 revision

A recreation of the <bit> header from C++20, containing a series of bitwise operations. Like the standard version, most of the functions in cpp98/bit.h will only exist for valid unsigned integral types.

Note that in standard C++, std::bit_cast has been blessed by the standard as a special exception to object lifetime rules. Obviously that is not something I can replicate here. Use it with appropriate caution. The endian enum is not included as it is an implementation-defined quantity, and even suggested implementations don't cover all compilers still on C++98.

Features

bit_cast Reinterpret object representation of one type as another
byteswap Reverses the bytes in a given integer value
has_single_bit Checks if a number is an integral power of two
bit_ceil Finds the smallest integral power of two not less than the given value
bit_floor Finds the largest integral power of two not greater than the given value
bit_width Calculates the smallest number of bits needed to represent the given value
rotl Calculates the result of a bitwise left rotation
rotr Calculates the result ofa bitwise right rotation
countl_zero Calculates the number of consecutive zero bits, starting at the most significant bit
countl_one Calculates the number of consecutive one bits, starting at the most significant bit
countr_zero Calculates the number of consecutive zero bits, starting at the least significant bit
countr_one Calculates the number of consecutive one bits, starting at the least significant bit
popcount Counts the number of one bits in an unsigned integer

Sample code

#include <iostream>
#include "cpp98/bit.h"


int main(){

    unsigned char c = 87;
    std::cout << dp::countr_zero(c) << '\t' << dp::countl_zero(c) << '\n';
    std::cout << dp::popcount(c);

}

Clone this wiki locally