Search code examples
cassemblyx86-64bit-shift

Difference between sarq and shrq


Name: Value

%rdi: 0x6

%rax: 0x4

What is the difference between sarq and shrq?

If I had sarq $1, %rdi how would this value look? What does shrq %rdi do?


Solution

  • sarq is arithmetic right shift for quadword, and shrq is logical right shift for quadword. The difference is that arithmetic shift will fill the vacant bits with the leftmost bit (aka the sign bit) while the logical right shift will just fill them with 0.

    For positive numbers, their behavior is the same. For negative numbers, their behavior is totally different.

    For example, assume %rax = 16 (0x0000 0000 0000 0010). Both sar $4, %rax and shrq $4, %rax will set the %rax to 1 (0x0000 0000 0000 0001).

    Now if %rax = -16 (0xffff ffff ffff fff0). sar $4, %rax will set %rax to -1 (0xffff ffff ffff ffff) while shr $4, %rax will set %rax to 1152921504606846975 (0x0fff ffff ffff ffff).

    To use which instruction depends on the data type and what you want to do. The C >> operator uses sar for signed data types and shr for unsigned ones.