I presume that the lower 4 bits are first using y = (a ^ b) to obtain a chart of the bit (x is unknown)
xxxx0000
Then change the bit pattern with y = ~ y
xxxx1111
Then we define the first 0 with y ^ = (y + 1)
xxx11111
Then move n times to the right y β = n
0000xxx1
If it is not equal to nul, then the lower n bits were equal. So my solution would be
int are_lowest_n_bits_of_a_and_b_equals(int n,int a, int b) /* return 0 if not equal, or non zero if equal */ { int y=~(a^b); return (y^(y+1))>>n; }
It seems to work even for n = number_of_bits (int), thanks to the propagation of the sign bit in the shift in the arithmetic shift to the right, but if it was ever UB, we can just check (a == b) in that case the edges.
source share