Basically, the behavior you get when overflowing integers with subtraction, but for a given number of bits. The obvious way, assuming a signed integer:
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);
}