I've read other questions about this, but they don't answer my question.
In the following code I understand that it checks if that bit is set, but my question is why?
bool test(uint8_t& flag)
{
return flag & (1 << 4);
}
I don't get why it returns a bool and it works, flag is uint8_t and 1 << 4 should be something like this 00010000 (I think). Why does that code return the value of the desired single bit and not the rightmost or something like that?
The C++ draft standard section 4.12 Boolean conversions says (emphasis mine):
A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.
So any non-zero value will be converted to true.
You expressed some doubts as to the result of 1 << 4 we have a quick way to check this using std::bitset:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<8> b1(1<<4);
std::cout << b1 << std::endl ;
return 0;
}
and we can see the result is indeed 00010000 since bitwise and only set a bit to 1 if the bit in both operands are 1 then the result of flag & (1 << 4) will only be non-zero if bit 5 of flag is also 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