C quick calculation of next multiple of 4?

前端 未结 7 1888
无人共我
无人共我 2020-12-15 05:04

What\'s a fast way to round up an unsigned int to a multiple of 4?

A multiple of 4 has the two least significant bits 0, right? So I could

7条回答
  •  温柔的废话
    2020-12-15 05:20

    If you want the next multiple of 4 strictly greater than myint, this solution will do (similar to previous posts):

    (myint + 4) & ~3u
    

    If you instead want to round up to the nearest multiple of 4 (leaving myint unchanged if it is a multiple of 4), this should work:

    (0 == myint & 0x3) ? myint : ((myint + 4) & ~3u);
    

提交回复
热议问题