Created
August 13, 2019 10:21
-
-
Save Lucretia/3799b2f6961d99cf55cf9a6bbf53ee20 to your computer and use it in GitHub Desktop.
Testing no + operator add and swap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Ported to Ada from https://www.geeksforgeeks.org/add-two-numbers-without-using-arithmetic-operators/ | |
with Ada.Text_IO; use Ada.Text_IO; | |
with Interfaces; use Interfaces; | |
procedure XOR_Alg is | |
type Unsigned_Integer is mod 2 ** Integer'Size; | |
function "xor" (Left, Right: Integer) return Integer is | |
begin | |
return Integer (Unsigned_Integer (Left) xor Unsigned_Integer (Right)); | |
end "xor"; | |
function "and" (Left, Right: Integer) return Integer is | |
begin | |
return Integer (Unsigned_Integer (Left) and Unsigned_Integer (Right)); | |
end "and"; | |
procedure Swap (X, Y : in out Unsigned_16) is | |
begin | |
if X /= Y then | |
X := X xor Y; | |
Y := Y xor X; | |
X := X xor Y; | |
end if; | |
end Swap; | |
function Add (X, Y : in Unsigned_16) return Unsigned_16 is | |
A : Unsigned_16 := X; | |
B : Unsigned_16 := Y; | |
C : Unsigned_16; | |
begin | |
while B /= 0 loop | |
C := A and B; | |
A := A xor B; | |
B := Shift_Left (C, 1); | |
end loop; | |
return A; | |
-- return (X xor Y) or Shift_Left (X and Y, 1); | |
end Add; | |
function Add (X, Y : in Integer) return Integer is | |
A : Integer := X; | |
B : Integer := Y; | |
C : Integer; | |
begin | |
while B /= 0 loop | |
C := A and B; | |
A := A xor B; | |
B := Integer (Shift_Left (Unsigned_64 (C), 1)); | |
end loop; | |
return A; | |
end Add; | |
A : Unsigned_16 := 56; | |
B : Unsigned_16 := 98; | |
begin | |
Swap (A, B); | |
Put_Line ("A: " & Unsigned_16'Image (A) & " B: " & Unsigned_16'Image (A)); | |
Put_Line ("A: " & Unsigned_16'Image (Add (32, 11))); | |
Put_Line ("A: " & Unsigned_16'Image (Add (32, 15))); | |
Put_Line ("A: " & Unsigned_16'Image (Add (80, -57))); | |
end XOR_Alg; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment