C++ 如何在数组中存储位字符串?

C++ 如何在数组中存储位字符串?,c++,c,C++,C,如何计算8位字符串中1的出现次数。例如10110001。 位字符串取自用户。比如10110001 应该使用什么类型的数组在c中存储此位字符串?简短而简单。使用(C++) #包括 #包括 int main() { std::bitset mybitstring; std::cin>>mybitstring; std::cout简短。使用(C++) #包括 #包括 int main() { std::bitset mybitstring; std::cin>>mybitstring; std::co

如何计算8位字符串中1的出现次数。例如10110001。 位字符串取自用户。比如10110001 应该使用什么类型的数组在c中存储此位字符串?

简短而简单。使用(C++)

#包括
#包括
int main()
{
std::bitset mybitstring;
std::cin>>mybitstring;
std::cout简短。使用(C++)

#包括
#包括
int main()
{
std::bitset mybitstring;
std::cin>>mybitstring;

std::cout完全不要使用数组,使用std::string。这样可以更好地处理错误。您可以编写如下代码:

bitset <8> b;
if ( cin >> b ) {
    cout << b << endl;
}
else {
    cout << "error" << endl;
}
位集b;
如果(cin>>b){

cout完全不要使用数组,使用std::string。这为您提供了更好的错误处理的可能性。您可以编写如下代码:

bitset <8> b;
if ( cin >> b ) {
    cout << b << endl;
}
else {
    cout << "error" << endl;
}
位集b;
如果(cin>>b){
来自黑客的喜悦:

For machines that don't have this instruction, a good way to count the number
of 1-bits is to first set each 2-bit field equal to the sum of the two single
bits that were originally in the field, and then sum adjacent 2-bit fields,
putting the results in each 4-bit field, and so on. 
因此,如果
x
是一个整数:

x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF);
x
现在将包含1位的数字。只需使用8位值调整算法。

来自黑客的喜悦:

For machines that don't have this instruction, a good way to count the number
of 1-bits is to first set each 2-bit field equal to the sum of the two single
bits that were originally in the field, and then sum adjacent 2-bit fields,
putting the results in each 4-bit field, and so on. 
因此,如果
x
是一个整数:

x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F);
x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF);
x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF);

x
现在将包含1位的数量。只需使用8位值调整算法。

您可能会使用
无符号int
将这些位存储在C中

如果您使用的是GCC,那么您可以使用
\uuu内置\uuPopCount
来计算一位:

内置函数:
int\uuu内置的popcount(未签名的intx)

返回x中的1位数


这应该可以解析为支持它的CPU上的一条指令。

您可能会使用
无符号int
将这些位存储在C中

如果您使用的是GCC,那么您可以使用
\uuu内置\uuPopCount
来计算一位:

内置函数:
int\uuu内置的popcount(未签名的intx)

返回x中的1位数


这应该可以解析为支持它的CPU上的一条指令。

如果它这么短,就使用您认为最容易使用的指令。您是否可以为该操作编写代码。这样,位字符串就可以用来计算“1”的出现次数.使用。如果它这么短,就使用你认为最容易使用的。你能为那个操作写代码吗。这样那个位字符串就可以用来计算“1”的出现次数。使用。