有符号字节中的计数 1
Count 1's in a signed byte
我在这里有这个函数来计算字节中的1
位。但是,当我尝试将char
值设置为200时,它会中断。但是,如果我将char
更改为unsigned char
,它会起作用。我很好奇为什么。
int bit_counter (char b){
char count = 0;
while (b != 0){
if (b & 0x01){
count ++;
}
b = b >> 1;
}
return count;
}
I have solved this issue. I masked all the bits, but the most significant bit.
int bit_counter (char b){
char count = 0;
while (b != 0){
if (b & 0x01){
count ++;
}
b = b >> 1;
b = (b & 0x7F);
}
return count;
}
这个非常棘手,我们必须研究char
的组成。首先,当您的函数中有0 < b < 128
时,它工作得很好。
您使用的是一个签名字符。有符号字符由一个符号位和7个数据位组成。这意味着您只能拥有-128到127之间的7位值。此处为字符表示。
当您指定b = 200
时,您有一个溢出,这意味着您超过127,它将取另一个由200表示的值。我假设编译器采用200的二进制表示,即:
1100 1000:粗体的1是符号位的值(此处表示为负数(。
当您对b的内容进行位移位时,您只移位数据位。所以接下来的迭代看起来像:
1110 0100
1111 0010
1111 1001
11111 1111
它对应于值-1(参见二的补码。char的零表示为0000 0000。所以b永远不会是0,你陷入了一个无限循环。。。
如果你想解决这个问题,你可以使用unsigned char
(没有符号位,用数据代替(,或者你可以迭代b类型的大小:
int bit_counter (char b){
char count = 0;
// sizeof(type) = byte size and -1 because there is the sign bit
for(int bitIndex = 0; bitIndex < (sizeof(char) * 8) - 1; ++bitIndex){
if (b & 0x01){
count ++;
}
b = b >> 1;
}
return count;
}
在现代c++中最好使用标准库std::bitset
。正如许多人在评论中所说,你可能已经理解使用内置类型的缺点。
std::bitset<N>
有一个函数count
,它会返回设置为true(1(的位。
的几个例子
std::bitset<8> testBitSet { "11110000" }; //std::bitset<N> -- N (num of bits)
std::cout << testBitSet.count() << std::endl; //4
std::bitset<8> testBitSet2{ "11111111" };
std::cout << testBitSet2.count() << std::endl; //8
//The first 8 are considered
std::bitset<8> testBitSet4{ "00000011111111" }; //2
std::cout << testBitSet4.count() << std::endl;
//Construcing with a number
std::bitset<8> testBitSetWithNum(200);
std::cout << testBitSetWithNum.count() << std::endl; //3
std::cout << testBitSetWithNum << std::endl; //11001000
相关文章:
- 如何将字节数组元素替换为修改的十六进制 ASCII 符号?
- 将字符串转换为无符号字符数组/字节数组
- 将(N 个字节)无符号字符指针转换为浮点数和双 C++
- 一种将 Dart 中的字节数据转换为 C++ 中的无符号字符*的有效方法?
- 什么是 16 字节有符号整数数据类型?
- C++ - 将任何文件的字节读取到无符号字符数组中
- 如何通过组合红色和蓝色无符号字节来优化混合?
- C++ 从函数返回无符号字节
- 视觉C++转换和写入值为 10 的无符号 int 给出 5 个字节
- 计算表示有符号整数所需的最小字节数
- 用std :: stringstream读取/写作无符号字节
- 水平求和SSE无符号字节矢量的最快方法
- 如何在GLSL中将浮点量化为无符号字节
- C++模需要在两个*无*符号字节之间进行减法转换才能工作,为什么
- 从2个16位有符号字节中获取有符号整数
- 为什么我的无符号字节需要两倍大
- 饱和减去/加法无符号字节
- NEON向量化无符号字节积和:(a[i]-int1) * (b[i]-int2)
- 4个有符号字节打包成32位无符号字节
- 无符号字节与换行符冲突