University of Leeds

Bitset

Introduction

The bitset class can be thought of as an array of bool elements and so essentially stores individual bits (i.e. 0 or 1, or true or false). This makes it useful for embedded systems programming in which we often need to access specific bits in registers etc.

It can be used by including the following header.

#include <bitset>

Creating bitsets

There are several ways to construct bitsets. We can create an empty bitset, or we can create one by specifying the value in decimal, hexadecimal or by providing a string that represents the binary value.

  std::bitset<8> my_empty_byte;
  std::bitset<8> my_byte(128);
  std::bitset<8> another_byte(0x0F);
  std::bitset<8> yet_another_byte(std::string("01010101"));

When we print the bitsets, we see the binary value.

// can print out the values
  std::cout << my_empty_byte << std::endl;
  std::cout << my_byte << std::endl;
  std::cout << another_byte << std::endl;
  std::cout << yet_another_byte << std::endl;

This gives the following output.

00000000
10000000
00001111
01010101

Modifying bits

Once we have created a bitset, it is simple to set, reset or flip individual bits.

  std::cout << "Now modify a bitset:\n";
  // we can modify the bitsets
  my_byte.reset(7);  // clear bit 7
  my_byte.set(0);    // set bit 0
  my_byte.flip(1);   // flip bit 1
  std::cout << my_byte << std::endl;

This will produce the following output.

Now modify a bitset:
00000011

We can also access a specific bit using the [] operator, just like accessing an element of an array. An alternative is to use the test() member function. This returns a bool which reflects the state of that bit particular bit.

std::cout << "Access individual bits:\n";
std::cout << "Bit 7 is " << my_byte[7] << std::endl;
std::cout << "Can also do it with the test() member function:\n";
std::cout << "Bit 0 is " << my_byte.test(0) << std::endl;

This would produce the following output:

Access individual bits:
Bit 7 is 0
Can also do it with the test() member function:
Bit 0 is 1

Bit-wise operations

Bitsets naturally support bit-wise operations (that is, logical operations on corresponding pairs of bits). It is possible to do AND (&), OR (|), XOR (^) and NOT (~).

// some bit-wise operations
std::bitset<4> a(5);
std::bitset<4> b(3);
std::bitset<4> z = a | b;  // OR
std::cout << a << " OR " << b << " = " << z << std::endl; 

This would produce the following output:

0101 OR 0011 = 0111

Conversion

The bitset class also has handy methods for converting a bitset to (unsigned) integers and strings.

// we can convert a bitset to an integer (unsigned long)
  unsigned long byte_value = my_byte.to_ulong();
  std::cout << "The byte has a value " << byte_value << std::endl;
  // and also to a string
  std::string byte_string = my_byte.to_string();
  std::cout << "The byte string is " << byte_string << std::endl;

This could would produce the following output.

The byte has a value 3
The byte string is 00000011