[fpc-devel] Unexpected behaviour of bit operators

Ondrej Pokorny lazarus at kluug.net
Fri May 17 18:06:13 CEST 2019


On 17.05.2019 10:47, Marco Borsari via fpc-devel wrote:
> Does this is an effect of some multiplication overflow, or is it a bug?

Both the bit operations and the arithmetic opretaions return integers as 
results and not words:
https://www.freepascal.org/docs-html/ref/refsu46.html
https://www.freepascal.org/docs-html/ref/refsu45.html#x148-17000012.8.1

The c:=... overflows - you get a range check error:

c:=(a XOR b)*(a SHL 5+b SHR 2); // range check error

Just add a couple of word() casts where you need the integer-result to 
be casted to word:

program test;
{$r+}
const n=12;
s=1 shl n;
var a,b,c,h1,h2:word;
begin
a:=77;
b:=0;
h1:=word((a XOR b)*(a SHL 5+b SHR 2)) SHR (16-n);
h2:=word((a XOR b)*(a SHL 5+b SHR 2)) AND ((s-1) SHL (16-n)) SHR (16-n);
writeln(h1,',',h2);
c:=word((a XOR b)*(a SHL 5+b SHR 2));
h1:=c SHR (16-n);
h2:=c AND ((s-1) SHL (16-n)) SHR (16-n);
writeln(h1,',',h2);
ReadLn;
end.

Ondrej




More information about the fpc-devel mailing list