计数C++负数中的1位
Counting number of 1 bits in C++ negative number
以下函数:
int numOnesInBinary(int number) {
int numOnes = 0;
while (number != 0) {
if ((number & 1) == 1) {
numOnes++;
}
number >>= 1;
}
return numOnes;
}
只适用于正数,因为在负数的情况下,执行>>操作时,它总是在最左边的位上加一个1。在Java中,我们可以使用>>,但如何在C++中实现呢?我在一本书中读到,我们可以在C++中使用无符号整数,但我不明白如何使用,因为无符号整数不能表示负数。
将number
强制转换为unsigned int并对其执行计数:
int numOnesInBinary(int number) {
int numOnes = 0;
unsigned int unumber = static_cast<unsigned int>(number);
while (unumber != 0) {
if ((unumber & 1) == 1) {
numOnes++;
}
unumber >>= 1;
}
return numOnes;
}
// How about this method, as hinted in "C Book" by K & R.
// Of course better methods are found in MIT hackmem
// http://www.inwap.com/pdp10/hbaker/hakmem/hakmem.html
//
int numOnesInBinary(int number) {
int numOnes = 0;
// Loop around and repeatedly clear the LSB by number &= (number -1).
for (; number; numOnes++, number &= (number -1));
return numOnes;
}
无符号整数允许在简单循环中计数位。
如果我们谈论值,从有符号到无符号的转换将导致无效结果:
char c = -127;
unsigned char u = (unsigned char)c; // 129
但如果我们只谈论形式,它不会改变:
1 0 0 0 0 0 0 1 == decimal signed -127
1 0 0 0 0 0 0 1 == decimal unsigned 129
所以选为unsigned只是一个技巧。
count表示整数n中的集合位数如果整数的大小是32位,则
int count =0;
int n = -25 //(given)
for(int k=0;k<32;k++){
if ((n >> k) & 1){
count++;
}
}
return count;
相关文章:
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- C / C++ 移位/偏移/向左或向右移动位图?
- 对字符串进行位操作
- 如何在24位SDL_Surface上设置像素的颜色
- 将浮动的heightmap数组导出为16位原始值
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- C++Union/Struct位域的实现和可移植性
- 为什么C++逐位AND运算符在不同大小的操作数中表现为这样
- 将按位if条件转换为普通if条件
- 对字符数组中的元素执行逐位操作
- 将位字段导出到数组
- 将应用程序从32位移植到64位时出现问题
- 逐位操作的隐式类型转换
- 位阵列上的快速AND运算
- 64位机器上的C++内存对齐
- 一位朋友将模板函数缩写为clang和gcc
- 宽度为奇数的16位纹理为片状
- 如何打印boost多精度128位无符号整数
- 正在解码MSVC 32位版本的程序集(作业).没有手术做什么