Posted on Leave a comment

Compare integer without if case

[code language=”delphi”]
// 1 -> 0
// 0 -> 1
function flip(g: integer): integer;
begin
result := 1 xor g;
end;

// 1 – positive
// 0 – negative
function sign(f: integer): integer;
begin
result := flip((f shr 31) and $1);
end;

function getMax(a, b: integer): integer;
var
k, q: integer;
begin
k := sign(a – b);
q := flip(k);
result := a * k + b * q;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
a, b: integer;
begin
a := strtoint(Edit1.Text);
b := strtoint(Edit2.Text);
Edit3.Text := inttostr(getMax(a, b));
end;
[/code]

but
if a=maxint-3, b=-20 then there is a integer overflow.

solution

[code language=”delphi”]
function getMax(a, b: integer): integer;
var
k, q, c, sa, sb, sc: integer;
signofa: integer;
signofc: integer;
begin
c := a – b;
sa := sign(a);
sb := sign(b);
sc := sign(c);
signofa := sa xor sb;
signofc := flip(sa xor sb);
k := signofa * sa + signofc * sc;
q := flip(k);
result := a * k + b * q;
end;
[/code]

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.