I am unable to understand how does the direction flag work in x86
. The text in my lectures say that it increments or decrements the source or destination register but that does not make sense with its name. Can someone explain what it does?

- 328,167
- 45
- 605
- 847
2 Answers
This flag is used in string operations, and specifies if strings begin at a low address and proceed to higher addresses or vice versa.
For string instructions, ECX
has the number of iterations, DS:ESI
has the source address and ES:EDI
has the destination (hence the s in ESI
and the d in EDI
).
After each iteration, ECX
is decremented by one, and ESI
and EDI
are either incremented or decremented by the element size (1 for byte operations, 2 for word operations etc) according to EFLAGS.DF
.
If EFLAGS.DF
is 0
, ESI
and EDI
are incremented, otherwise they're decremented.

- 122,701
- 101
- 260
- 319
-
So it increases or decreases the string accordingly. If a string starts with a lower address it would add to it or in the other case perform the opposite, right? – Apr 30 '12 at 07:41
-
Nathan Fellman, @Jerry Coffin, I think that the default behaviour is to copy from the beginning of a memory block (DF cleared). In what cases one would want to copy a memory block from the end instead (DF set)? – golem Aug 20 '15 at 15:05
-
2@golem: Consider copying stacks, that generally grow downwards. Consider comparing (not copying) strings, where you want to check backwards until the first difference. In these cases the direction matters. – Nathan Fellman Aug 20 '15 at 17:43
-
Another use case I've just discovered is when you want to insert a substring into a string and for that move the tail part to the right. In that case you have to copy byte from the len(str) location to len(str)+len(substr), then len(str-1) to len(str-1)+len(substr), and so on going downwards in the memory. – golem Sep 19 '15 at 16:44
Let's take rep movsb
as an example of an instruction that depends on the direction flag.
When you do a rep movsb
, you supply a source address in esi
, a destination address in edi
, and count in ecx
. The processor basically executes a loop. In the normal case (when the direction flag is clear) it increments esi
and edi
each iteration of the loop, so you initialize them to point to the beginning of the source and destination blocks you're copying. While executing the REP MOVSB
, the processor increments the source and destination addresses until it reaches the end of the block being copied.
When the direction flag is set, the processor decrements the registers instead. This means you need to start with them pointing to the end of the memory block you're copying. Instead of starting from the beginning and copying to the end, it starts at the end and copies backward until it gets to the beginning.

- 476,176
- 80
- 629
- 1,111