Coding Ada: Bitwise operators
In Ada, you can find similar bitwise operators to other languages: and, or, xor, and operators that shift left and right. The trick is that they use modular types. These types are unsigned and have “wrap-around” semantics. Consider the following declaration:
subtype byte is unsigned_8; package byteIO is new ada.text_io.modular_io(byte); x, y, z: byte;
This defines an integer type whose values range from 0 to 255 (on most processors), i.e. the integers that will fit in a byte. Since it’s “modular”, it means that arithmetic operations on the type wrap around (i.e. if you add 130 + 130, you will get 4. With this declaration, you can create binary numbers:
x := 2#00011110#; y := 2#11110100#; z := 2#11110000#;
Here x=30, y=244, and z=240. So we can then use bitwise operators (found in the Ada package Interfaces) to swap the numbers:
x := x xor y; y := y xor x; x := x xor y;
The numbers can be printed out with this code:
put_line(unsigned_8'image(x)); put_line(unsigned_8'image(y));
You can also use put from the sub-package byteIO:
byteIO.put(item => z, base => 2);
If we want to convert a number input from integer to type byte, we can do so in the following manner:
w: integer;
get(w);
z := byte'val(integer'pos(w));
byteIO.put(item => z, base => 2);
The byte’val returns the base type of byte. For example, if the value input by the user is 17 (w), then the value assigned to z will be 10001. What about shift operators? There is shift_left() and shift_right(). Here’s an example:
zs: byte; zs := shift_left(z,1); byteIO.put(item => zs, base => 2);
If the user inputs 12, then the value of zs will be 24, as it has been shifted left 1 bit.
spqr