Little Tricks

I.

Given: x, n where n is a power of 2, mask = ~(n – 1)

x & mask = the greatest multiple of n that is less or equal to x

(x + (n – 1)) & mask = the smallest multiple of n that is greater or equal to x

II.

x & (x – 1) clears x’s rightmost 1 to 0 in binary

2条评论

  1. 十二月 29, 2006 在 10:20 下午

    Great bit twiddling hack, I can’t recall if it is actually part of the Hacker’s Delight book.🙂 Anyhow, good logic!

  2. bombie said,

    一月 2, 2007 在 11:16 上午

    I know, right? Saw this in someone’s code, had to record it down.😛


发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: