std :: string的C位运算符
作者:互联网
我的问题是关于如何在C std :: string上使用按位运算符.通过重载或功能无关紧要.
std :: string的工作XOR / ^函数示例:
std::string XOR(std::string value, std::string key)
{
std::string retval(value);
long unsigned int klen = key.length();
long unsigned int vlen = value.length();
unsigned long int k = 0;
unsigned long int v = 0;
for (; v < vlen; v++) {
retval[v] = value[v] ^ key[k];
k = (++k < klen ? k : 0);
}
return retval;
}
我现在缺少的是NOT /〜,AND /&的替代品.加上OR / |.
示例C代码(最后两行想要它…… :-P):
//note: matrix_content[][] holds unsigned, *checked* integers...
// char(foo) works...
std::string vertical_master = "";
for (unsigned short int k = 0; k < axis_max; k++) {
for (unsigned short int l = 0; l < axis_max; l++) {
horizontal_master += char(matrix_content[l][k]);
vertical_master += char(matrix_content[k][l]);
}
}
std::string vertical_shift1_0 = vertical_master;
usigned short int bit = "@"; //<- just an example... chatched via
// std::string::substr() and std::string::c_str()
for (unsigned long int x = 0; x < axis_max; x++) {
vertical_shift1_0 += char(bit);
}
std::string vertical_shift2_0;
for (unsigned long int x = 0; x < axis_max; x++) {
vertical_shift2_0 += char(0);
}
vertical_shift2_0 += vertical_master;
std::string vertical_or = ~(vertical_shift1 | vertical_shift2);
std::string vertical_and = ~(vertical_shift1_0 & vertical_shift2_0);
在PHP / Perl中,我可以做坏事:-像这样的事情
$vertical_shift1_0 = $vertical_master.str_repeat(chr(0), $axis_max);
$vertical_shift2_0 = str_repeat(chr(0), $axis_max).$vertical_master;
$vertical_or = chunk_split(~($vertical_shift1 | $vertical_shift2), $axis_max, chr(170));
$vertical_and = chunk_split(~($vertical_shift1_0 & $vertical_shift2_0), $axis_max, chr(170));
……我很想念它;-).然而XOR工作.我怎样才能得到AND / OR / NOT?
解决方法:
通过[]运算符从字符串中取出char后,可以使用所需的所有按位运算符. C/C++将有符号/无符号字符视为数字类型(不幸的是).
如果您正在执行许多按位操作,则可以考虑使用其中一个专用位数据结构
> ST000> bitset,用于固定长度的位集
> bit_vector来自动态长度位集的提升
标签:c,string,bitwise-operators,stdstring 来源: https://codeday.me/bug/20190730/1583365.html