I want to check if the 4th byte of my array is equal to any of these : 0xe0 0xe1 0xe2 0xe3 0xe4 0xe5 0xe6 0xe7 0xe8 0xe9 0xeA 0xeB 0xeC 0xeD 0xeE 0xeF. My friend told me to use the statement (array[3] & 0xf0) == 0xe0. This works but i can't actually understand why.
Remember, with bitwise AND (&
) operation, the Nth bit of result is only equal to 1 if both corresponding bits of the operands are equal to 1.
So &-ing 0xf0
to the value of 4th byte (array[3]
) essentially replaces the lowest half of that byte with 0, leaving the highest one intact.
1010 1010
&
1111 0000
==== ====
1010 0000
^^^^ ^^^^
|| ||
as is zeroed
Now all that remains is check that value against 0xe0
.