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
  • 62,720
  • 18
  • 132
  • 197
3

Something like

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

should do the trick.

Roger Rowland
  • 25,297
  • 11
  • 71
  • 110