The fundamental criterion for numbers tested for equality here is that the remainder of size / 4 is 2. This can be detected using the modulo % operator:
size % 4 == 2
Then the question arises how many times to divide unit by 2. For the above examples:
- For
size == 2 , unit /= 8 (matches all 3 conditions); - For
size == 6 , unit /= 4 (corresponds to the second 2 conditions); - For
size == 10 , unit /= 2 (matches the last condition).
So, the smaller the number, the more it divides by 8. If the maximum size set to 10, unit is divisible by 2 ^ (1 + (10 - size) / 4) . This can be summarized using the right-shift operator:
unit >>= 1 + (10 - size) / 4
or, more generally:
unit >>= 1 + (max_number - size) / 4
where max_number % 4 == 2 .
Setting max_number = 254 (256 is asked in the question, but will not be present in the expression, the last verified number will be 254) and note that we only apply this in the case 2 <= size <= 254 , we can express the final answer as:
if (size % 4 == 2 && size >= 2 && size <= 254) { unit >>= 1 + (254 - size) / 4; }
Actually, the condition can be expressed more briefly (but, of course, less readable) as:
if ((size & 0xffffff03) == 2)
As @PaulBoddington noted, care must be taken with the size of the right shift: if the unit is int and the number of bits shifted is greater than 31, then unit should simply be set to zero.
Andy turner
source share