Bit Hack - Round off to multiple of 8

前端 未结 7 2076
情歌与酒
情歌与酒 2021-01-31 12:42

can anyone please explain how this works (asz + 7) & ~7; It rounds off asz to the next higher multiple of 8.

It is easy to see that ~7 produces 11111000 (8bit repre

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-31 13:14

    Adding 7 does not produce a multiple of 8. The multiple of 8 is produced by anding with ~7. ~7 is the complement of 7, which is 0xffff fff8 (except using however many bits are in an int). This truncates, or rounds down.

    Adding 7 before doing that insures that no value lower than asz is returned. You've already worked out how that works.

提交回复
热议问题