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

how to store the bit string in array?

本文关键字:存储 字符串 数组      更新时间:2023-10-16

如何计算8位字符串中出现1的次数。如10110001。位串取自用户。就像10110001什么类型的数组应该用来存储这个位字符串在c?

简短明了。使用std::bitset (c++)

#include <iostream>
#include <bitset>
int main()
{
  std::bitset<8> mybitstring;
  std::cin >> mybitstring;
  std::cout << mybitstring.count(); // returns the number of set bits
}

Ideone在线测试

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

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

但是没有办法找出是哪个字符引起的错误

您可能会使用unsigned int将这些位存储在c中。

如果你使用的是GCC,那么你可以使用__builtin_popcount来计数1位:

内置功能:int __builtin_popcount (unsigned int x)
返回x中1位的个数。

From hacker's delight:

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位值。