如何在数组中存储位字符串
how to store the bit string in array?
如何计算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位值。
相关文章:
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 在向量 C++14(无限制联合)的结构内的联合中创建和存储字符串
- 如何存储字符串列表
- 在向量中存储字符串存在 SEG 错误
- 指针存储字符串?
- 逐个字母存储字符串并打印
- 将字符数组转换为字符串并存储字符串?
- 当分配动态内存以存储字符串副本时,程序会中断
- 在C/C++中存储字符串、数组和指针,哪种方法更有效
- 我们如何以 7 位格式存储字符串
- C 存储字符串输入为CString
- TVItem lparam存储字符串
- C++以相反的顺序存储字符串
- 如果存储字符串的char数组小于字符串,则C++实际存储字符串
- 为什么我的 SetBookTitle 不存储字符串
- 如何在 C 中有效地存储字符串的映射
- 如何使用好友运算符存储字符串
- 如何在 C++ 中存储字符串和整数串联的变量
- 如何在 c++ 中存储字符串数组
- 存储字符串