How to assign bitset value from a string after ini

2019-08-29 04:06发布

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?

标签: c++ bitsets
2条回答
时光不老,我们不散
2楼-- · 2019-08-29 04:30

Something like

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

should do the trick.

查看更多
Explosion°爆炸
3楼-- · 2019-08-29 04:34

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];
查看更多
登录 后发表回答