How to assign bitset value from a string after initializaion

天涯浪子 提交于 2019-12-13 04:32:25

问题


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?


回答1:


Something like

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

should do the trick.




回答2:


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];


来源:https://stackoverflow.com/questions/17360953/how-to-assign-bitset-value-from-a-string-after-initializaion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!