快速获取一个正数的掩码

 方式1

int mask = num;
mask |= mask >> 1;
mask |= mask >> 2;
mask |= mask >> 4;
mask |= mask >> 8;
mask |= mask >> 16;

经过5次移位和异或操作,即使1在最左处,也可以覆盖整个序列

示例:

100001 -> 1 |

110000 -> 2 |

111100 -> 4 |

111111 -> 8 |

111111 -> 16 |

111111

 

 方式2

long mask = 1;
while (mask <= num) {
    mask <<= 1;
}
int k = (int)mask - 1;

 

a ^ b == ~a & b

^:相同则 0 相异则 1

&:同 1 则 1

1 ^ 1 == ~1 & 1 = 0

0 ^ 1 == ~0 & 1 = 1

0 ^ 0 == ~0 & 0 = 0

posted @ 2021-10-18 13:16  oumae  阅读(38)  评论(0编辑  收藏  举报