Skip to content

Instantly share code, notes, and snippets.

@xiazhibin
Last active April 11, 2018 08:44
Show Gist options
  • Save xiazhibin/6cc01ad10a47d53ad96276fda8bedb76 to your computer and use it in GitHub Desktop.
Save xiazhibin/6cc01ad10a47d53ad96276fda8bedb76 to your computer and use it in GitHub Desktop.
一些位运算的技巧

n个bit能表示的最大数值

-1 ^ (-1<<n) = 2^n-1

原理:将最右n位变成1

  • -1 表示 1111 1111 1111 1111
  • 移4位后 1111 1111 1111 1111 0000
  • 高位舍去,异或
     1111 1111 1111 0000
^    1111 1111 1111 1111             
---------------------------            
     0000 0000 0000 1111

PS: a & mask = a % mask

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment