I was using std::bitset<N>
in my program and needed to find the least significant set bit and did the trivial calculation as below :
int num = 5;
int res = num & (-num);
After which the least significant bit of num
is set in res
and rest all are 0
's. This works as -5
is represented in 2's complement notation.
But I found std::bitset<N>
doesn't have any operator overload for unary operator -
which would have given me the 2's complement for the underlying bits. Is there a trivial way to implement the 2's complement with std::bitset<N>
? I could always use operator ~
to flip the bits and loop over them doing the sum and carry starting from LSB to MSB, but I was looking for a solution which would avoid that.
std::bitset
doesn't provide any complement methods. Since you would have to calculate the complement yourself with operator~
and an additional loop, simply skip operator~()
and search for the LSB directly:
template <int N>
size_t least_significant_bit(const std::bitset<N> &bt){
for(size_t i = 0; i < bt.size(); ++i){
if(bt.test(i))
return i;
}
}
I guess it can't get more trivial than that ;).
Note that the result of least_significant_bit
isn't specified if there's no bit at all. One could return N
or change the loop in order to test bt.test(N)
which would throw an exception, but after all it doesn't really make sense to look for a LSB in a nulled bitset.
Further note, you can use std::bitset<N>::operator[]
instead of std::bitset<N>::test
if you're not interested in boundary checks.
this should do it unless I am missing something
std::bitset<N> twos_comp = std::bitset<N>((~input).to_ulong() + 1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With