8086 assembly - how to add 2 bytes whose sum will be larger than a byte

assembly, x86, x86-16

Solution

Say, you need to add two bytes, each having a value from 0 to 255 inclusive.

You need to add those bytes and save the value of the carry flag after the addition, which will be the 9th bit of the sum.

Here's how you could do it:

mov al, byte1
mov ah, 0 ; ax = byte1
add al, byte2
adc ah, 0 ; ax = byte1 + byte2

Note, I'm using `mov ah, 0` instead of `cbw` when extending an 8-bit value to 16 bits. `cbw` works if your byte is supposed to represent negative values as well as positive, IOW, if it's in the range -128 to 127 instead of 0 to 255. And you're saying you've got 150 (0x96) and 215 (0xD7), so they have to be used as unsigned or non-negative values. If you apply `cbw` on them anyway, you'll get: -106 (0xFF96) and -41 (0xFFD7). And that's hardly your original numbers, right?

Problem

Ok so the question is simple. If i have 2 random bytes, say 150 (a[0]) and 215(b[0]) and i want to add them. obviously their sum won't fit in a byte so if i add them i will get an overflow. I've tried storing one of the bytes in al and doing a cbw, so that i would have the same quantity only represented on the word ax, and add the second byte to that, but there's something i'm failing to understand since it doesn't work. Here is a sample code: ``` data segment a db 150,182,211 b db 215,214,236 data ends code segment start: mov ax,data mov ds,ax lea si,a ; these 2 shouldn't be here since i realised eventually that ; i could use lea di,b ; a constant for memory addressing and not necessarily a ; a register mov ax,0000 mov bl,a[0] mov al,b[0] cbw adc bx,ax ; so this didn't work out well mov ax,0000 mov al,a[0] cbw ; convert one of the bytes into a word mov cx,ax ; and save it in cx mov al,b[0] cbw ; also convert the other byte into the word ax add ax,cx ; add the two words ; and that also failed ```

Original source