5

I am unsure of what the cbw command actually does. I have a snippet of code:

mov  ax,0FF0h
cbw
idiv ah

How does the value of ax change after cbw?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
raphnguyen
  • 3,565
  • 18
  • 56
  • 74
  • Look it up in any copy of Intel or AMD's ISA reference manual: https://www.felixcloutier.com/x86/CBW:CWDE:CDQE.html. See also [When and why do we sign extend and use cdq with mul/div?](//stackoverflow.com/q/36464879) and also [What does cltq do in assembly?](//stackoverflow.com/a/45386217) for a table of cbw / cwde / cwd / etc. equivalents in terms of movsx, for both Intel and AT&T syntax. – Peter Cordes Mar 20 '19 at 20:04
  • 2
    Dividing by `AH` after sign-extending into AX is exceptionally weird. It will fault for non-negative AL (because AH=0), or it will divide by `-1` for negative AL. (Again faulting with `#DE` for AL=80h, because -128 / -1 = +128 overflows 8-bit AL.) This is like the worst most inefficient attempt to take the absolute value of AL. – Peter Cordes Mar 20 '19 at 20:07
  • @PeterCordes `cbw`, `cwde`, `cdqe` all three uses same opcode. So how does processor chooses `al->ax`, `ax->eax`, `eax->rax` ? Same for `cwd`, `cdq`, `cqo` triplet. – Sourav Kannantha B Jul 17 '21 at 15:03
  • @SouravKannanthaB: Prefixes, exactly like for other 16/32/64-bit opcodes. You can even see the full machine code including prefixes for all of those instructions in my answer I already linked in my first comment, [What does cltq do in assembly?](https://stackoverflow.com/a/45386217). For details of prefixes, see [Is there a default operand size in the x86-64 (AMD64) architecture?](https://stackoverflow.com/q/68289333) – Peter Cordes Jul 17 '21 at 17:02

1 Answers1

11

The cbw instruction sign-extends a byte into a word. In this case, it'll take the sign bit of AL (which happens to be 1) and copy it into every bit of AH.

This means that the two's-complement value of AX will be the same, but the binary representation will be different.

The value of AX after the cbw instruction will be FFF0h (a 16-bit -16 value, just like AL was originally an 8-bit -16)

  • Thanks. I understand your explanation of the sign bit of `AL` being 1, since it is negative, but I am a bit confused as to why `AL` is originally an 8-bit -1. Isn't `AL` -16 originally (with the sign bit equal to 1)? – raphnguyen Nov 01 '11 at 02:12
  • 1
    The last zero in 0FF0h was overlooked. AX should become 0FFF0h after CBW. – Alexey Frunze Nov 01 '11 at 05:29