Bit Hack - Round off to multiple of 8

2020-05-18 23:58发布

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 representation) and hence switches off the last 3 bits ,thus any number which is produced is a multiple of 8.

My question is how does adding asz to 7 before masking [edit] produce the next higher[end edit] multiple of 8 ? I tried writing it down on paper

like :

1 + 7 = 8  = 1|000 (& ~7) -> 1000
2 + 7 = 9  = 1|001 (& ~7) -> 1000
3 + 7 = 10 = 1|010 (& ~7) -> 1000
4 + 7 = 11 = 1|011 (& ~7) -> 1000
5 + 7 = 12 = 1|100 (& ~7) -> 1000
6 + 7 = 13 = 1|101 (& ~7) -> 1000
7 + 7 = 14 = 1|110 (& ~7) -> 1000
8 + 7 = 15 = 1|111 (& ~7) -> 1000

A pattern clearly seems to emerge which has been exploited .Can anyone please help me it out ?

Thank You all for the answers.It helped confirm what I was thinking. I continued the writing the pattern above and when I crossed 10 , i could clearly see that the nos are promoted to the next "block of 8" if I can say so.

Thanks again.

7条回答
Evening l夕情丶
2楼-- · 2020-05-19 00:36

Well, if you were trying to round down, you wouldn't need the addition. Just doing the masking step would clear out the bottom bits and you'd get rounded to the next lower multiple.

If you want to round up, first you have to add enough to "get past" the next multiple of 8. Then the same masking step takes you back down to the multiple of 8. The reason you choose 7 is that it's the only number guaranteed to be "big enough" to get you from any number up past the next multiple of 8 without going up an extra multiple if your original number were already a multiple of 8.

In general, to round up to a power of two:

unsigned int roundTo(unsigned int value, unsigned int roundTo)
{
    return (value + (roundTo - 1)) & ~(roundTo - 1);
}
查看更多
男人必须洒脱
3楼-- · 2020-05-19 00:37

It's actually adding 7 to the number and rounding down.

This has the desired effect of rounding up to the next multiple of 8. (Adding +8 instead of +7 would bump a value of 8 to 16.)

查看更多
闹够了就滚
4楼-- · 2020-05-19 00:38

The +7 isn't to produce an exact multiple of 8, it's to make sure you get the next highest multiple of eight.

edit: Beaten by 16 seconds and several orders of quality. Oh well, back to lurking.

查看更多
成全新的幸福
5楼-- · 2020-05-19 00:38

Well, the mask would produce an exact multiple of 8 by itself. Adding 7 to asz ensures that you get the next higher multiple.

查看更多
手持菜刀,她持情操
6楼-- · 2020-05-19 00:38

Without the +7 it will be the biggest multiple of 8 less or equal to your orig number

查看更多
地球回转人心会变
7楼-- · 2020-05-19 00:39

Uhh, you just answered your own question??? by adding 7, you are guaranteeing the result will be at or above the next multiple of 8. truncating then gives you that multiple.

查看更多
登录 后发表回答