operator / () and operator % ()

unsigned_int<> supports both "division" operators / (divide) and % (modulus).

The rules for unsigned division are that with two inputs a and b, d = a / b and m = a % b then a == (d * b) + m. See Reversable Test

Notes:

The operators /= and %= are also defined with a specialization for unsigned_int<> and generic versions for other (inbuilt and user defined) numeric types.

Tests

Large Left

Test the case where the left hand side is larger than the right.

unsigned_int< 128 > left( "0xAA55AA55AA55AA55AA55AA55AA55AA55" );
unsigned_int< 32 > right( "0xAA55AA56" );

unsigned_int< 128 > d = left / right;
unsigned_int< 32 > m = left % right;

CHECK( d == unsigned_int< 128 >( "0xFFFFFFFF7F405FD058B4359D" ) );
CHECK( m == unsigned_int< 32 >( "0x23106597" ) );

std::cout << std::hex << std::uppercase << d << '\n' << m << '\n';

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

FFFFFFFF7F405FD058B4359D
23106597
Ok

Large Right

Test the case where the left hand side is smaller than the right.

unsigned_int< 32 > left( "0xAA55AA56" );
unsigned_int< 128 > right( "0xAA55AA55AA55AA55AA55AA55AA55AA55" );

unsigned_int<128> d = left / right, m = left % right;

CHECK( d == 0 );
CHECK( m == unsigned_int<128>( "0xAA55AA56" ) );

std::cout << std::hex << std::uppercase << d << '\n' << m << '\n';

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

0
AA55AA56
Ok

operator / () Test

unsigned_int< 128 > a( 100 ), b( a ), c( 10 );
unsigned u = 10;

b /= c;
CHECK( b == 10 );
CHECK( (a / c) == 10 );
CHECK( (a / 10) == 10 );
CHECK( (1000 / a) == 10 );

u = 1000;
u /= a;
CHECK( u == 10 );

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

Ok

operator % () Test

Some simple tests, see also Division Tests.

unsigned_int< 128 > a( 10 ), c( 99 );
unsigned u = 10;

c %= a;
CHECK( c == 9 );
CHECK( (c % a) == 9 );
CHECK( (99 % a) == 9 );
CHECK( (c % 10) == 9 );

u = 99;
u %= a;
CHECK( u == 9 );

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

Ok

Reversable Test

unsigned_int< 128 > a( 100 ), b( 99 ), d, m, r;

d = a / b;
std::cout << "d = a / b: " << d << '\n';

CHECK( d == 1 );

m = a % b;
std::cout << "m = a % b: " << m << '\n';

CHECK( m == 1 );

r = (d * b) + m;
std::cout << "(d * b) + m: " << r << '\n';

CHECK( r == a );

a = 10;

d = a / b;
std::cout << "d = a / b: " << d << '\n';

CHECK( d == 0 );

m = a % b;
std::cout << "m = a % b: " << m << '\n';

CHECK( m == 10 );

r = (d * b) + m;
std::cout << "(d * b) + m: " << r << '\n';

CHECK( r == a );

Test Result: gcc34 Passed, msvc80 Passed, msvc71 Passed

Output

d = a / b: 1
m = a % b: 1
(d * b) + m: 100
d = a / b: 0
m = a % b: 10
(d * b) + m: 10
Ok