How to perform sign-extension?

That is the way I would have done it.

My only suggestion is that the ibits() function in your expression is unnecessary.

sext = shifta(shiftl(x,bit_size(x)-n),bit_size(x)-n)

would work just as well.