-1

I am trying to perform an arithmetic shift right in Delphi. I can't get it to work though, it keeps giving incorrect answers.

Here is my code;

  lValue := offset;
  asm
    mov cl,32
    sar lValue,cl
  end;
  hgh := lValue and $FFFFFFFF;

When offset is set to 1024 and the shift right is set to 32, hgh should equal 0. In my code, hgh = 1024.

Jake Evans
  • 978
  • 5
  • 13
  • 33
  • 3
    If I recall correctly the instruction only supports shifts up to 31 (5-bit displacement value). – 500 - Internal Server Error Feb 05 '15 at 21:22
  • @500-InternalServerError - how would I make it do more? – Jake Evans Feb 05 '15 at 21:25
  • @500-InternalServerError's comment is absolutely correct: "... all other IA-32 processors (starting with the Intel 286 processor) do mask the shift count to 5 bits, resulting in a maximum count of 31." There is nothing really wrong about intermixing Pascal and BASM, but you have to be very careful with assembler (just as usual). – Free Consulting Feb 05 '15 at 21:35
  • How come in C/C++ it works correctly? – Jake Evans Feb 05 '15 at 21:38
  • It cannot work "correctly" on IA-32 processors. – Free Consulting Feb 05 '15 at 21:41
  • @Free It's the "you just have to be very careful" that's the problem. – David Heffernan Feb 05 '15 at 21:46
  • @Jake the x86 instruction set is comprehensively documented by Intel. Did you read this? If not, why not? You'll find your answer there. – David Heffernan Feb 05 '15 at 22:17
  • 2
    What do you mean when you say C++ "works correctly"? Shifting a 32-bit integer more than 31 bits to the right with the `>>` operator is undefined. Shifting right by using inline assembler will give the same results as your Delphi code because the assembler is the same in either case. – Rob Kennedy Feb 05 '15 at 22:58
  • 1
    Your title seems to indicate that you think there's a difference between logical and arithmetic shifts, but in this case, there is none. For non-negative inputs, they behave identically. – Rob Kennedy Feb 05 '15 at 23:00

1 Answers1

0

You should conditionally shift by 31 bits for numbers greater or equal to 32

OCTAGRAM
  • 618
  • 6
  • 12