#Clearing Bits using BITWISE OPERATORS
29 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.
ping!
so would 101011 become 101000 and would 1111 become 0000 and would 10101 become 10100?
I don’t think this is possible, bit wise operations operate on individual bits so they have no way of differentiating if a bit is at the end or beginning
However if you allow yourself to use ctz (count tailing zeros), you should be able to do something like this
int n; //input
int rot_num = ctz(~n); // count trailing 1s
n >>= rot_num; // shift right
n <<= rot_num; // shift back left, replacing last rot_num bits with 0
In computer software and hardware, find first set (ffs) or find first one is a bit operation that, given an unsigned machine word, designates the index or position of the least significant bit set to one in the word counting from the least significant bit position. A nearly equivalent operation is count trailing zeros (ctz) or number of trailing...
There’s an implementation here maybe you could do something
while the last bit is set, shift one to the right
done
@digital iron can you use loops at all? Because internally those use if
32
32
32
Interesting assignment. Feels like code golf.
I cannot do it without a loop.
Wow that’s very clever
It is. I tip my hat to thee @simple pilot
Annoyingly, I had a voice in my head telling me there is a clever solution.
I am just not clever enough to come up with it myself.
I can only marvel at its simplicity when confronted with it.
Why did it get deleted
btw the original response from 5921 was x&(x+1)
Dang that's genius
This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.
https://en.cppreference.com/w/cpp/numeric/countr_one theres also c++20 way of counting how many consecutive bits there are
@digital iron
This question thread is being automatically closed. If your question is not answered feel free to bump the post or re-ask. Take a look at !howto ask for tips on improving your question.
@digital iron Has your question been resolved? If so, run !solved :)
!solved