C++ Bitset

A limitation of the bitset is that size must be known at compile time i.e. size of the bitset is fixed.

Syntax

bitset<size> variable_name(initialization);

Initialization

  1. Uninitialized - all bits set to 0

    bitset<size> variable_name;
  2. Initialization with decimal integer

    bitset<size> variable_name(DECIMAL_NUMBER);
  3. Initialization with binary string

    bitset<size> variable_name(string("BINARY_STRING"));
    bitset<size> variable_name("BINARY_STRING");

Utility Functions

to_string()

Converts bitset to std::string.

to_ulong()

Converts bitset to unsigned long.

to_ullong()

Converts bitset to unsigned long long.

  1. Convert a number to its binary - 32 bits : string bit = bitset<32>(x).to_string();

  2. Convert a binary representation to the decimal number - 32 bits : long long decimal = bitset<32>(bit).to_ullong();

Reference : https://www.geeksforgeeks.org/cpp-bitset-and-its-application/

Last updated