SHR vs. SAR

It came up in an interview today when SAR (shift arithmetic right) is used instead of SHR (shift and rotate right) the simple rule (on gcc at least and probably cl) if it’s a signed it will use SAR and not SHR. Makes total sense of course after looking at it. Left shift is always SHL regardless of sign.

int a = 0x80000000;
int b = 0x00000001;
a = a >> 5;
b = b << 5;

Produces:

movl   $0x80000000,-0x4(%rbp)
movl   $0x1,-0x8(%rbp)
sarl   $0x5,-0x4(%rbp)
shll   $0x5,-0x8(%rbp)

After shifting the variable will be: 0xfc000000

This sometimes surprises some people who assume that shifting is always the rotate shift operation (that shifts in zeros)

WikiBooks Shift and Rotate

This entry was posted in interviewing and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>