Bitwise operations

13.1 - Bitset


The std::bitset type represents a fixed-size bit sequence. Bitsets can be created from and converted into integers and strings.

Since bitsets are printable, they can be used to print the binary representation of other values.

Example 1
Creating a 32-bits long bitset from an int:

int n = 42;
std::bitset<32> bits(n); // 00000000000000000000000000101010

Example 2
Creating an 8-bits long bitset from a char:

char c = 'L';
std::bitset<8> bits(c); // 01001100

Task

Write a program that accepts an ASCII character and prints out its binary representation in 8 bits.

  • Use std::cin and a char variable to input the character.
  • Use std::bitset<8> constructor to get the bitset of it.
  • Use std::cout to print out the bitset.
#include <iostream> #include <bitset> int main() { }