简体   繁体   中英

What happens if I increment a value in a 16-bit register that has already maximum value?( Assembly 8086)

I've placed the value of BX register to FFFF and I did the command inc BX , The value turned into 0000 . Where did the value go? I checked the flags but I still couldn't come up with an explanation.

0xFFFF + 1 = 0x10000 and you are storing the result into 16 bit register, so it gets truncated to 0x0000 (the result would need at least 17 bits to avoid truncation).

Just like when you do mov bx,0x8000 add bx,0x8000 -> bx == 0x0000 too.

Flags reflect the situation according to the definition in Intel manual, add will set all flags accordingly, inc preserves carry flag and modifies all other flags.

In this case of zero result both will set ZF=1, but only add will modify CF=1.

This inconsistency between add/adc x,1 vs inc x and sub/sbb x,1 vs dec x is intentional design by Intel engineers to allow for simple creation of loops where the two instructions work in tandem, inc/dec not disrupting the chain of adc/sbb instructions, like addition of arbitrary long integers stored in memory:

  ; 16 bit x86 real mode code, will do "destination += source;"
  ; ds:si = source integer, ds:di = destination integer
  ; cx = length in words of integers (bytes = 2*cx)
  ; modifies all involved registers and ax
  clc      ; clear carry flag to not affect result of addition
add_loop:
  lodsw    ; ax = another word of source integer, si+=2
  adc  [di], ax    ; destination_word += source_word + carry
  ; this did also set new carry for next word, so it must be preserved
  lea  di,[di+2]   ; advance also di by 2, with LEA to preserve carry
  dec  cx          ; test if all word have been processed (preserves carry)
  jnz  add_loop    ; but zero flag is being set by the `dec` = loop condition
  ret      ; here the long integers addition is done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM