Integer subtraction with wrap around for N bits

后端 未结 4 1406
逝去的感伤
逝去的感伤 2021-01-05 20:56

Basically, the behavior you get when overflowing integers with subtraction, but for a given number of bits. The obvious way, assuming a signed integer:

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-05 21:28

    For unsigned arithmetic, and mask the results, e.g.:

    template
    unsigned
    sub_wrap( unsigned v, unsigned s )
    {
        return (v - s) & ((1 << bits) - 1);
    }
    

    More generally, you can use the modulo operator:

    template
    unsigned
    sub_wrap( unsigned v, unsigned s )
    {
        return (v - s) % modulo;
    }
    

    (Wrapping on n bits is the equivalent of modulo 2^n.)

    For signed arithmetic, it's a bit more complex; using the mask, you'll have to sign extend the results (supposing 2's complement).

    EDIT: Using sehe's suggestion for signed arithmetic:

    template
    int
    sub_wrap( int v, int s )
    {
        struct Bits { signed int r: bits; } tmp;
        tmp.r = v - s;
        return tmp.r;
    }
    

    Given this, sub_wrap<5>( -16, 28 ) gives -12 (which is correct—note that 28 cannot be represented as signed int in 5 bits); sub_wrap<6>( -16, 28 ) gives 20.

提交回复
热议问题