0

I know it is possible to initialize bitsets using an integer or a string of 0s and 1s as below:

bitset<8> myByte (string("01011000")); // initialize from string

Is there anyway to change value of a bitset using an string as above after initialization?

dahma
  • 75
  • 2
  • 6

2 Answers2

3

Yes, the overloaded bitset::[] operator returns a bitset::reference type that allows you to access single bits as normal booleans, for example:

myByte[0] = true;
myByte[6] = false;

You even have some other features:

myByte[0].flip(); // Toggle from true to false and vice-versa
bool value = myByte[0]; // Read the value and convert to bool
myByte[0] = myByte[1]; // Copy value without intermediate conversions

Edit: there is not an overloaded = operator to change a single bit from a string (well it should be a character) but you can do it with:

myByte[0] = myString[0] == '1';

Or with:

myByte[0] = bitset<8>(string("00000001"))[0];
myByte[0] = bitset<8>(myBitString)[0];

Equivalent to:

myByte[0] = bitset<1>(string("1"))[0];
Adriano Repetti
  • 65,416
  • 20
  • 137
  • 208
3

Something like

myByte = bitset<8>(string("01111001"));

should do the trick.

Roger Rowland
  • 25,885
  • 11
  • 72
  • 113
  • It's worth noting that the first character in the string corresponds to the rightmost (least significant) bit of the bitset, and the last character in the string corresponds to the leftmost (most significant) bit of the bitset. Therefore, when you access individual bits using the [] operator or any bitset-specific operations, the indexing starts from the rightmost (least significant) bit, which is at index 0. For example, you can access the fourth bit (which has value 1) using myByte[3]. – Shayan Jun 26 '23 at 09:10