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

Using Logical Operators On Integers

I saw lately a thread on this site about using logical operators on integers in C. However, I didn’t really understand how this worked so here I provide two examples and I hope someone can provide a detailed explanation for them:

  1. int result = 1000 & 255
  2. int result = 1000 || 255

>Solution :

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

Decimal 1000 is binary 11 1110 1000. Decimal 255 is binary 1111 1111. First, they are converted to signed int, which is usually 32 bits wide.

Taking & of them sets the bit at all positions where both bits of the operands are set:

  0000 0000 0000 0000 0000 0011 1110 1000
  0000 0000 0000 0000 0000 0000 1111 1111
& ---------------------------------------
  0000 0000 0000 0000 0000 0000 1110 1000

This is decimal 232. Taking | would have set the bit at all positions where at least one bit is set, i.e. would have produced binary 11 1111 1111, which is decimal 1023. Taking ^ would have set the bit at all positions where exactly one of the bits is set, i.e.

  0000 0000 0000 0000 0000 0011 1110 1000
  0000 0000 0000 0000 0000 0000 1111 1111
^ ---------------------------------------
  0000 0000 0000 0000 0000 0011 0001 0111

&& is not a binary operation. It simply returns 1 if and only if both operands are non-zero. || returns 1 if and only if at least one of the operands is non-zero. In other cases, they return 0, respectively.

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