问题描述:

Is there any semantic meaning when doing an and operation of a number and its two's complement?

for example:

int x = 31;

int result = x & (-x)

Does result hold any semantic meaning?

网友答案:

The result will have one bit set, which is the least-significant set bit in x. Put another way, the result indicates how "round" x is in terms of powers of 2: 1 for odd numbers, 2 for multiples of 2, 4 for multiples of 4, etc.

This is because -x is equal to ~x + 1. x & ~x is 0, of course, but by adding 1 to ~x all of the lowest-order 1s in ~x will become 0s, and the lowest-order 0 in ~x will become a 1, and this will be the only bit that x and ~x + 1 have in common.

相关阅读:
Top