简体   繁体   English

计算在C ++中为二进制数设置为1的位

[英]Count the bits set in 1 for binary number in C++

How many bits are set in the number 1 in one binary number of 15 digits. 在一个二进制数15位的数字1中设置了多少位。

I have no idea how to start this one. 我不知道如何开始这个。 Any help/hints? 任何帮助/提示?

Smells like homework, so I'll be all vague and cryptic. 闻起来像家庭作业,所以我会模糊和神秘。 But helpful, since that's what we do here at SO. 但是很有帮助,因为这就是我们在SO所做的。

First, let's figure out how to check the first bit. 首先,让我们弄清楚如何检查第一位。 Hint: you want to set all other bits of the variable to zero, and check the value of the result. 提示:您希望将变量的所有其他位设置为零,并检查结果的值。 Since all other bits are zero, the value of the variable will be the value of the first bit (zero or one). 由于所有其他位都为零,因此变量的值将是第一位(零或一)的值。 More hint: to set bits to zero, use the AND operation. 更多提示:要将位设置为零,请使用AND操作。

Second, let's move the second bit to the first position. 其次,让我们将第二位移到第一位。 There's an operation in C++ just for that. C ++中有一个用于此的操作。

Third, rinse and repeat until done. 第三,冲洗并重复直至完成。 Count them ones as you do so. 在你这样做的时候算一下。

EDIT: so in pseudocode, assuming x is the source variable 编辑:所以在伪代码中,假设x是源变量

CountOfOnes=0
while X != 0
    Y = the first bit of X          (Y becomes either 0 or 1)
    CountOfOnes = CountOfOnes + Y
    X = X right shift 1             

Specifically for C++ implementation, you need to make X an unsigned variable; 特别是对于C ++实现,您需要使X成为无符号变量; otherwise, the shift right operation will act up on you. 否则,右移操作将对您起作用。

Oh, and << and >> operators are exactly bitwise shift. 哦,<<和>>运算符完全按位移位。 In C++, they're sometimes overridden in classes to mean something else (like I/O), but when acting on integers, they perform bit shifting. 在C ++中,它们有时在类中被覆盖以表示其他东西(如I / O),但是当对整数进行操作时,它们会执行位移。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM