What is the optimal way to sign-extend the lowest n
bits of an integer?
For example, let’s take a 16-bit integer (the decimal value 34)
0000000000100010
The sign-extend function sext(x,n)
, with n = 6
should return:
1111111111100010
^
FEDCBA9876543210 ! bit index
In other words, the function is supposed to pad the left side with ones, if the bit at position n-1
is set.
The solution I have right now is
! Sign-extend the lowest n bits of x
pure function sext(x,n)
integer(int16), value :: x
integer, value :: n
integer(int16) :: sext
sext = shiftl(ibits(x,0,n),bit_size(x)-n)
sext = shifta(sext,bit_size(x)-n)
end function
Is there a better combination of bit intrinsics to achieve this?
A full program is provided in Compiler Explorer at the link: https://godbolt.org/z/Ko8nscjPq