C quick calculation of next multiple of 4?

前端 未结 7 1879
无人共我
无人共我 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:44

    This is branch-free, generally configurable, easy to understand (if you know about C byte strings), and it lets you avoid thinking about the bit size of myInt:

    myInt += "\x00\x03\x02\x01"[myInt & 0x3];
    

    Only downside is a possible single memory access to elsewhere (static string storage) than the stack.

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