Integer subtraction with wrap around for N bits

后端 未结 4 1364
逝去的感伤
逝去的感伤 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:21

    I suppose this should work:

     struct bits
     {
         signed int field : 5;
     };
    
     bits a = { -16 };     
     bits b = {  28 };
    
     bits c = { a.field - b.field };
     std::cout << c.field << std::endl;
    

    I'm pretty sure the field width won't work with a const template argument... and hence this is less generic. It should, however, avoid manual tinkering. Will post test soon

    Update It turns out my answer wasn't incorrect after all. It is just that the sample input (28) cannot be represented in 5 bits (signed). The outcome of the above is -12 (see http://ideone.com/AUrXy).

    Here is, for completeness, a templated version after all:

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

提交回复
热议问题