Pithole when using Bitwise Operations

I was attempting to do my Operating Systems programming assignment using C++ programming language(what I share applies to other languages too!) when I encountered this small mistake of mine that took me a few hours of debugging. Consider this expression: arr[i]&ONBIT[j]==0. On first sight, most people who are new to bitwise operators or seldom use them will assume a left-to-right operation. However, this did not turn out to be true when all elements of arr are 0. On a random thought while I finally took a break after a few hours of debugging attempts, it came to me that maybe the following actually happened: arr[i]&(ONBIT[j]==0), which always evaluates to 0 and hence false. It turns out that this was the case. Hence, making things explicit like (arr[i]&ONBIT[j])==0 gave me the result that I wanted.

Lesson learnt here: when unfamiliar with operator precedence, always go a Google search to confirm, or use parentheses to make the intended meaning explicit. This is something that is taught in fundamental programming courses but tends to get forgotten fast due to preference of shortcuts and shorter syntax. Hope this helps you when doing bitwise arithmetic on numbers next time 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s