【发布时间】:2022-01-24 17:04:11
【问题描述】:
我这里有这个函数来计算一个字节中的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;
}
【问题讨论】:
-
如果您使用的是 C++ 20,则有 std::popcount。
-
char的最大值是127(假设它是一个 8 位有符号值) -
如果 8 位
char在您的平台上签名(而且很可能是),则不存在值 200 的 8 位签名字符。合法值为 -128....127。也就是说,并且保护您如何在char中存储这样的值,您可能遇到的是对有符号值进行算术右移的符号扩展。 See this answer. -
尝试使用
uint8_t而不是char。uint8_t会告诉编译器你想要一个无符号的 8 位变量。 -
@Eljay 对于
signed,它的实现定义了负值会发生什么,因此它可能变为正值(即使大多数实现“移入”@987654336 @ 保持消极)