Year 2020

Arithmetic right shift in Delphi

A little tip if you do need a "Arithmetic shift right" operation in Delphi:

function SARLongint(Value,Shift:longint):longint;
{$if defined(cpu386)}assembler; register;
asm
 mov ecx,edx
 sar eax,cl
end;
{$elseif defined(cpux64)} assembler;
asm
{$if defined(Windows) or defined(Win32) or defined(Win64)}
 mov eax,ecx
 mov ecx,edx
 sar eax,cl
{$else}
 push rcx
 mov eax,edi
 mov ecx,esi
 sar eax,cl
 pop rcx
{$ifend}
end;
{$else}
begin
 Shift:=Shift and 31;
 result:=(longword(Value) shr Shift) or (longword(longint(longword(0-longword(longword(Value) shr 31)) and longword(0-longword(ord(Shift<>0) and 1)))) shl (32-Shift));
end;
{$ifend}