Count the bits set in 1 for binary number in C++ - c++

How many bits are set in the number 1 in one binary number of 15 digits.
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.
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.
Second, let's move the second bit to the first position. There's an operation in C++ just for that.
Third, rinse and repeat until done. Count them ones as you do so.
EDIT: so in pseudocode, assuming x is the source variable
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; 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.

Related

How can I turn the number 0-8 into the 0-8th binary position in C++?

I am trying to use the integers 1-8 to represent the binary positions D0-D7.
I'm at a loss at how to transform this. I tried taking the most significant bit, but that doesn't really work for this situation..
Any thoughts or pointers to resources on this topic? It's for addressing in an OLED screen.
I'm trying to think of a clever solution in C++. I could just make a switch table, but I thought there must be a cooler way to do it with bit manipulation!
For example
int x = 7
y = convert(x)
if (y == 0b01000000)
print("Success!!")
Thank you for any and all help!!
What you're looking for is bit shift - move all the bits in you variable either to left or right.
C++, among other languages uses << operator to shift bits to the left. You might find other bitwise operators useful for Your application.
Using this you can replace convert(x) with simply 1 << (x-1). That changes integers 1 to 8 (inclusive) to 0th to 7th bit position (inclusive).

What does this & operator mean here?

I was reading some tutorial about openGL in qt.
One of the mouse event slot has this code in it:
if (event->buttons() & Qt::LeftButton) {
rotationX += 180 * dy;
rotationY += 180 * dx;
updateGL();
}
what does the & operator do in the if statement?
is it exactly the same as == ?
It is not the same as ==. It is bitwise AND operator. What the expression does is that it takes the return value from event->buttons() and bitwise AND's it with the value represented by Qt::LeftButton. If the resulting value is non-zero the block is being executed.
In essence, it checks if the button specified by Qt::LeftButton is held down.
The reason why the bitwise AND operator is used here is something called a bitmask. What it means is that the return value of event->buttons() is just a value which has it's bits represent different kinds of states. What is done with the &-operator here is that it checks if certain bits(denoted by Qt::LeftButton) are being set(1) or unset(0) in the value returned by event->buttons(). The return value is zero if no tested bit is set, and non-zero, if at least one of the tested bits is set.
More details of how bitwise operations work can be found here: Wikipedia article about Bitwise operations
That will test that the value event=>buttons() has the bit Qt::LeftButton.
The result would be a 0, if it did not have that bit. and a Qt::LeftButton if it did include that bit.
it is a comparison to check the existence of a flag or bit value on a number
0001 == 1
0010 == 2
0011 == 3
1 & 2 == 0 (false)
1 & 3 == 1 (true)
2 & 3 == 2 (true)
essentially it is a match across the two values for their bit values.
(0001)
& (0010)
---------
(0000) //Neither have the same bit
(0011)
& (0010)
---------
(0010) //both have bit 2
(0101)
& (0110)
---------
(0100) // Both have the 3rd bit
(0111)
& (0110)
---------
(0110) // Both have the 2nd and 3rd bit
Boolean values in C languages are 0 for false. and anything non zero is true.
This proved that the 1st and 2nd bit are available in the number 3. however 1 and 2 do not have matching bits.
Look into bitwise operators. to get a better understanding.
http://en.wikipedia.org/wiki/Bitwise_operation
It's the bitwise AND operator.
0011
& 0101
------
0001
event->buttons() presumably returns a value that's a combination of bits where each bit represents one button. Qt::LeftButton is going to be a value that probably has just a single bit set in the position that corresponds to the "left button". Using bitwise AND (&) here ANDs the individual bits of those two values, and the condition will be considered true if the result is non-zero.
Since there's only one bit in Qt::LeftButton, the only way to get a non-zero value is if event->buttons() has the same bit set. (It may have other bits set too, but those go away when they're ANDed with the zero bits in those positions in Qt::LeftButton. Effectively, then, the expression means "true if and only if event->buttons() includes the bit represented by Qt::LeftButton".
This is the bitwise AND operator. The better question is: What's the job of the AND operator here? Why are we using such a "low-level" method here?
We got a set of flags here. The set of buttons held down is represented by event->buttons(). That means, it is the sum of all buttons held down. But every button is a unique power of two, so the sum of all buttons held down is a set of bits in an integer. I hope you understand this, as this is an essential part of how we can represent simple sets of limited elements in C / C++.
The point is, every bit in the so-called bitset represents one element in the set. So does every element have a unique number, which we have to be able to test against the bitset (if it is contained in the bitset).
If you want to test whether or not the left button was held down during the event, you have to check whether or not the bit is set in the bitset. This is done using the bitwise AND operator, as this combines all the bits of the operands bit for bit using the boolean AND operation. As you should know, the AND oepration returns true if and only if both of the input bits are true. So the bitwise AND operation works as a mask for the input bits. The right operand "filters out" the bits of the left operand which are present in the right operand.
As the if condition is interpreted as true if and only if the value is unequal zero, this equals the question whether or not the bits of the right operand also appear in the left operand. In this concrete scenario, this means: Is the value Qt::LeftButton bitwise contained in the value event->buttons(), or: is the bit represented by Qt::LeftButton contained in the bitset represented by event->button()?
Or simply: Is the left button held down?

length of continous bits 1 stream followed by 0

Was interview question, so looking for what could be non-obvious solutions.
Say there is big stream of 1111...111100000...000
find length (number) of 1.
You may assume here 1 is a Set Bit.
How it will change if 1 is symbol, say like aaa..aaaabbbb...bbbbb
One solution I could propose was look 1st bit/symbol, then keep doubling the interval, like then look 3rd, then 7th and so on. when ever you hit 0 or other symbol, then move back towards last position, again using divide and conquer.
If you have random access to the stream and the stream's length is known, you can do it with a variant of binary-search in O(log n).
Alternatively, you can & with 0x1 and, if zero, increment counter and right shift by 1. Or, you can check whether whole bytes (words, double words, quad words, etc) are non-zero to more quickly find the block where the ones start. Either way, that's O(n).
If you are to traverse the bit stream linearly you could process it in 32-bit chunks, performing a bitwise AND with 0xFFFFFFFF (all 1s) and updating your count accordingly.
This exploits the fact that modern CPUs can typically perform bitwise operations on 32-bit words as a single atomic action.
If the result of the AND is 0xFFFFFFFF then you know there are potentially more bits to follow and hence must inspect the next 32-bit word. Otherwise you simply increment your counter and cease looping.
binary search to find the index s.t. the ith bit is set and the (i+1)th isn't.
add a special case for the first bit being unset and the last bit being set, and you're done

bit shifting - replacing a section of a bitset with a new number

I have a list of numbers encoded as a boost dynamic bitset. I dynamically choose the size of this bitset depending on the maximum value any number in this list can take. So let's say I have numbers from just 0 to 7, I only need three bits and my string 0,2,7 will be encoded as
000010111.
I now need to change say the 2nd number in this list (2) to another number, say 4.
I thought the most efficient way to do this would be to represent 4 as a dynamic bitset of the same length as the list but with all other values set to 1, so 111111011. I would then bitshift this the required amount using with 1s used to fill in values to get 111011111, and then just bitwise AND this with the original bitset to get my desired result.
However, I cannot find a way to do these two things, as it seems with both initialisation of a bitset from an integer, and when bit shifting, the default and fill in values are always set to 0, not 1. How can I get around this problem, or achieve my goal in a different and efficient way.
Thanks
If that is really the implementation, the most general and efficient method I can think of would be to first mask off all the bits for the part you are replacing:
value &= 111000111;
Then "or" in the actual bits for that position:
value |= 000011000;
Hopefully someone here has a better trick for me to learn, but that's what I do.
XOR the old value and the new value:
int valuetoset = oldvalue ^ newvalue; // 4 XOR 2 in your example
Just shift the value you need to set:
int bitstoset = valuetoset << position; // (4 XOR 2) << 3 in your example
Then XOR again bitstoset with your bitset and that's it !
int result = bitstoset ^ bitset;
Would you be able to use a vector of dynamic bitsets? Depending on your needs that might be sufficient and allow for easy updates.
Alternately fill your new bitset similiarly to how you proposed, but exactly inverted. Then right before you do the and at the end, flip all the bits.
I guess your understanding of bitset is elementary wrong:
set means it is NOT ordered, and the idea of a bitset is, that only one bit is necessary to show that the element is in-/outside the set.
So your original set 0,2,7 would have 8 bits because 0..7 are 8 elements and NOT 3 * 3 (3 bits required to represent 0..7), and the bitmap would look like 10000101.
What you describe is just a "packed" coding of the values. In your coding scheme 0,2,7 and 2,0,7 would coded completly different, but in a bitset they are the same.
In a (real) bitset (if that is what you want) you can then really easy "replace" elements by removing the old and adding the new. This happens as T.E.D. describes it.
To get the right mask you can easily use shift operations. So imagine you start counting by 0, you get the mask for value x by doing: 1<<x;
So you remove element x from the set by
value &= ~(1<<x);
and add another elemtn x (which might be the same) with
value | = 1<<x;
From you comment you misuse the bitset, so the masks must be build different (and you already had an almost right idea how to build them).
The command with bitmask for removal of element at position p:
value &= ~(111 p);
This 111 is for the above example where you need 3 bit for a position. If you dont want to hardcode it, you could for just take the next power of 2 and subtract 1 and then you got your only-1-string.
And to add you would just take your suggestest bitlist that contains only the new element and OR it to your bitlist:
value |= new_element_bitlist;

How can I set all bits to '1' in a binary number of an unknown size?

I'm trying to write a function in assembly (but lets assume language agnostic for the question).
How can I use bitwise operators to set all bits of a passed in number to 1?
I know that I can use the bitwise "or" with a mask with the bits I wish to set, but I don't know how to construct a mask based off some a binary number of N size.
~(x & 0)
x & 0 will always result in 0, and ~ will flip all the bits to 1s.
Set it to 0, then flip all the bits to 1 with a bitwise-NOT.
You're going to find that in assembly language you have to know the size of a "passed in number". And in assembly language it really matters which machine the assembly language is for.
Given that information, you might be asking either
How do I set an integer register to all 1 bits?
or
How do I fill a region in memory with all 1 bits?
To fill a register with all 1 bits, on most machines the efficient way takes two instructions:
Clear the register, using either a special-purpose clear instruction, or load immediate 0, or xor the register with itself.
Take the bitwise complement of the register.
Filling memory with 1 bits then requires 1 or more store instructions...
You'll find a lot more bit-twiddling tips and tricks in Hank Warren's wonderful book Hacker's Delight.
Set it to -1. This is usually represented by all bits being 1.
Set x to 1
While x < number
x = x * 2
Answer = number or x - 1.
The code assumes your input is called "number". It should work fine for positive values. Note for negative values which are twos complement the operation attempt makes no sense as the high bit will always be one.
Use T(~T(0)).
Where T is the typename (if we are talking about C++.)
This prevents the unwanted promotion to int if the type is smaller than int.