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:
int result = 1000 & 255
int result = 1000 || 255
CodePudding user response:
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.