Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting bits from variables

I came across a part of code which extracts third bit of variable using

bool flag = (variable & 0x4) == 0x4;

However, the same can be achieved by bool flag = variable & 4;. Isn’t it? Any reason that this bit extraction specification need to have additional check with == 0x4 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s the same as far as the compiler is concerned. I didn’t even turn on optimizations and got the same assembly:

variable & 4 == 4 vs variable & 4

Thea above with with gcc. There’s some subtle differences with msvc, but it’s the same number of instructions.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading