Bitwise AND evaluates different under Delphi 3

Question:

Under Delphi 3 (all versions), on some occasions, bitwise arithmetic using "AND" against integers does not always render the same results as Delphi 2. How can I get around this?

Answer:

This is a known problem, where in certain circumstances, the compiler produces a sign extended negative result in a bitwise "AND" operation. The solution is to compare the result against zero, instead of comparing the result as being greater than zero. The following example demonstrates both the problem and the solution.

procedure TForm1.Button1Click(Sender: TObject);

var

  IntVal : Integer;

begin

  IntVal := 128 + 1;

  if (IntVal and 128) > 0 then

  ShowMessage('This never executes!');

end;

 

procedure TForm1.Button2Click(Sender: TObject);

var

  IntVal : Integer;

begin

  IntVal := 128 + 1;

  if (IntVal and 128) <> 0 then

  ShowMessage('This is correct!');

end;