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