I was working on a C project and i wrote the following line to check if the most significant bit of an int8_t is 1:
if (f & 0b10000000 == 0b10000000) {
and CLion threw up a warning, telling me 'Expression can be simplified to "f != 0"'
Would I be right in saying this is incorrect? I read over bitwise operations to be sure and I still feel like these are not equivalent operations, for instance f = 1 would return false with my expression, but this message is making me doubt myself.
Thanks for any help you can give!
The bitwise "and" operator &
has lower precedence than ==
.
Therefore, your expression if (f & 0b10000000 == 0b10000000)
is equivalent to if (f & (0b10000000 == 0b10000000))
.
If you just want to test bit 7, try if (f & 0b10000000)
. Any non-zero value will be treated as "true".
Also, yes: CLion is wrong. Your original expression is equivalent to if (f & 1)
, which tests bit 0 (probably not what you intended).
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