Adam Sh
Adam Sh

Reputation: 8577

Assembly - shr instruction turn on carry flag?

I saw the next code:

shr AL, 1
   jnc bit_0

I don't understand when the carry flag is turn on due to shr instrucrion?

Thanks

Upvotes: 6

Views: 17803

Answers (2)

Antonin GAVREL
Antonin GAVREL

Reputation: 11269

to add some clarifications :

shr AL, 1 ; it will (SH)ift (R)ight (1)x the value contained in AL register, which is 8 lower bits of AX register. Hence it will divide the value contained in AL by 2.

If AL was previously even like 0b100 (4) it will become 0b10 (2) and put 0 in the carry flag. Carry Flag is bit 0 in the flag register https://en.wikipedia.org/wiki/FLAGS_register

If AL was previously an odd value like 0b101 (5) then it will become 0b10 (2) and put 1 in the flag register. Hence the carry flag will act like a remainder if you divide by 2.

jnc bit_0 ; It will (J)ump to label 'bit_0' if (N)o (C)arry flag was set, i.e if the value was even (like 0b100 in the above example) before the shift.

Upvotes: 0

Matthew Slattery
Matthew Slattery

Reputation: 47058

shr AL, 1 moves all of the bits in AL right one place.

The original rightmost bit is shifted out of the AL register into the carry flag (and the new leftmost bit is set to 0). For example:

 +------------------------+               +------------------------+
 | 1  0  0  1  0  1  0  1 |               | 0  1  1  0  0  1  0  0 |
 +------------------------+               +------------------------+
    \  \  \  \  \  \  \  \       or          \  \  \  \  \  \  \  \
     \  \  \  \  \  \  \  \                   \  \  \  \  \  \  \  \
 +------------------------+ CF            +------------------------+ CF
 |(0) 1  0  0  1  0  1  0 | 1             |(0) 0  1  1  0  0  1  0 | 0
 +------------------------+               +------------------------+

In your comment on another answer:

My book gives the next example: Before shift: AL = 10101110 ; shr AL, 1 ; After shift: 01011100, CF = 1 ; Is it mistake?

If that's what it says, then yes. That's a left shift (shl AL, 1), not a right shift: the bits in AL have all been moved left by one place, and the carry flag has been set to the bit that was shifted out of the left-hand end.

Upvotes: 11

Related Questions