Bit Hack - Round off to multiple of 8

前端 未结 7 2065
情歌与酒
情歌与酒 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 12:54

    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.

    0 讨论(0)
  • 2021-01-31 12:54

    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.

    0 讨论(0)
  • 2021-01-31 13:00

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

    0 讨论(0)
  • 2021-01-31 13:03

    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);
    }
    
    0 讨论(0)
  • 2021-01-31 13:04

    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.)

    0 讨论(0)
  • 2021-01-31 13:06

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

    0 讨论(0)
提交回复
热议问题