Ada Programming/Types/mod

Description
Unsigned integers in Ada have a value range from 0 to some positive number (not necessarily 1 subtracted from some power of 2). They are defined using the keyword because they implement a wrap-around arithmetic.

Modulus

where ' is 0 and ' is Modulus - 1.

Wrap-around arithmetic means that 'Last + 1 = 0 = 'First, and 'First - 1 = 'Last. Additionally to the normal arithmetic operators, bitwise, and  are defined for the type (see below).

The predefined package (RM ) presents unsigned integers based on powers of 2

Unsigned_n  2**n;

for which also shift and rotate operations are defined. The values of n depend on compiler and target architecture.

You can use to sub-range a modular type:

Byte  256; Half_Byte Byte  0 .. 127;

But beware: the Modulus of Half_Byte is still 256! Arithmetic with such a type is interesting to say the least.

Bitwise Operations
Be very careful with bitwise operators, , , , when the modulus is not a power of two. An example might exemplify the problem.

Unsigned  2**5;   -- modulus 32 X: Unsigned := 2#10110#;    -- 22 X       = 2#01001#      -- bit reversal: 9 ( = 31 - 22 ) as expected

The other operators work similarly.

Now take a modulus that is not a power of two. Naive expectations about the results may lead out of the value range. As an example take again the operator (see  the RM for the others):

Unsigned  5; X: Unsigned := 2#001#; -- 1, bit reversal: 2#110# = 6 leads out of range

The definition of is therefore:

X = Unsigned'Last – X -- here: 4 – 1 = 2#011#

Wikibook

 * Ada Programming
 * Ada Programming/Types
 * Ada Programming/Keywords/mod

Ada Reference Manual


|Mod