sra
lyszt.net covers sra and other RISC-V instructions in more detail.
Encoding format
Description
sra is the second right shift, next to srl. The name stands for shift right arithmetic. The form below shifts rs1 right by the amount held in rs2.
sra rd, rs1, rs2
Like any right shift, it moves bits toward the low end and drops the ones that fall off. Its treatment of the empty top positions differs from srl.
RISC-V uses a signed scheme in which the top bit marks the sign, and a 1 there means the number is negative. srl fills the top with 0s, which erases the sign marker and turns a negative number into a large positive one. sra fills the top with copies of the existing sign bit, so the fill is 1s for a negative number and 0s for a positive one. The number keeps its sign.
sra divides a signed number by a power of two. A shift of 1 halves it, a shift of 3 divides it by 8, and negative numbers stay negative. The result rounds downward, toward the more negative value, so -7 shifted right by 1 gives -4 while the div instruction gives -3. Graphics and audio code usually accepts the downward rounding.
The RISC-V manual holds the shift amount in the lower 5 bits of register rs2. Five bits cover 0 to 31 places, so the other bits of rs2 have no effect. The manual describes sra as an arithmetic right shift, which copies the original sign bit into the vacated upper bits.
Use sra for signed numbers and srl for raw bit patterns or numbers that are never negative. For a fixed amount, use the constant form srai.
Example
li t0, -8 li t1, 1 sra t2, t0, t1 # t2 = -4 (sign-filled)
