Bitwise operations
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
Write a program that accepts an ASCII character and prints out its binary representation in 8 bits.
std::cin
and a char
variable to input the character.std::bitset<8>
constructor to get the bitset of it.std::cout
to print out the bitset.