Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CLion "Expression can be simplified" message on bitwise operation

Tags:

c

clion

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!

like image 742
Hghrmnd Avatar asked Jan 28 '23 23:01

Hghrmnd


1 Answers

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).

like image 134
r3mainer Avatar answered Feb 07 '23 17:02

r3mainer