Why is such complex code emitted for dividing a signed integer by a power of two?

后端 未结 3 825
囚心锁ツ
囚心锁ツ 2020-12-28 12:17

When I compile this code with VC++10:

DWORD ran = rand();
return ran / 4096;

I get this disassembly:

299: {
300:    DWORD r         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-28 12:54

    The reason is that unsigned division by 2^n can be implemented very simply, whereas signed division is somewhat more complex.

    unsigned int u;
    int v;
    

    u / 4096 is equivalent to u >> 12 for all possible values of u.

    v / 4096 is NOT equivalent to v >> 12 - it breaks down when v < 0, as the rounding direction is different for shifting versus division when negative numbers are involved.

提交回复
热议问题