سؤال

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?

هل كانت مفيدة؟

المحلول

Something like

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

should do the trick.

نصائح أخرى

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];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top