# Hot to test 16-bit numbers in assembler?

Page 1/3
| 2 | 3

I want to test 16-bit numbers. But how? For <, ==, >, <= and >=.

Edit: SBC works well, the problem were I was loading a DB (byte) into DE, so the MSB was wrong.

Are you sure? This example works quite well:

```org #4000
ld hl,4000
ld de,3000
or a
sbc hl,de
jp z,equal
jp p,positive
jp m,negative
ret

equal ld a,0
ret

positive ld a,1
ret

negative ld a,-1
ret
```

Why the "or a", SBC does not "clean" the flags by its own?

Better to test carry in stead of p/m, otherwise if de is large you will not get the result expected:

```ld hl,4000
ld de,3000
or a                  ; this resets carry so sbc doesn’t deduct one extra
sbc hl,de
jr z,hl_equals_de
jr c,hl_lessthan_de
jr nc,hl_greaterthan_de
```

To test >=, simply remove the `jr z` and use the `jr nc` (as nc includes zero).
To test <=, you can replace the `or a` by `scf` (deducts 1 more) and then `jr c`.

DarkSchneider wrote:

Why the "or a", SBC does not "clean" the flags by its own?

It is used to reset the carry flag. Also `and a` is often used for the same purpose (I usually do). Please refer to the Z80 user manual on SBC for the reason to reset the carry flag :).

DarkSchneider wrote:

Why the "or a", SBC does not "clean" the flags by its own?

SBC means "subtract with carry". So, SBC HL,DE -> HL = HL - DE - CY. Unfortunately there's no SUB HL,DE instruction, so if you just want to get HL=HL-DE then you have to use SBC HL,DE with a non-set (i.e. 0) carry. Using the OR A instruction before clears the carry flag.

Btw what is the fastest way to do such a test for signed 16bit values?
E.g. HL=-100, DE=50

One way is to add 8000H to both values before doing the test.

(Note that instead of actually adding 8000H, you can add 80H to h and d, or just toggle bit 7 of h and d.)

Quote:

I want to test 16-bit numbers. But how? For <, ==, >, <= and >=.

On MSX, the BIOS can do a non-destructive test for you. Just call the routine DCOMPR, or use a RST 20h for short.

sd_snatcher wrote:
Quote:

I want to test 16-bit numbers. But how? For <, ==, >, <= and >=.

On MSX, the BIOS can do a non-destructive test for you. Just call the routine DCOMPR, or use a RST 20h for short.

Nice! I like to use BIOS when possible.

sd_snatcher wrote:
Quote:

I want to test 16-bit numbers. But how? For <, ==, >, <= and >=.

On MSX, the BIOS can do a non-destructive test for you. Just call the routine DCOMPR, or use a RST 20h for short.

For reference, the BIOS does:

```ld a,h
sub d
ret nz
ld a,l
sub e
ret
```
Page 1/3
| 2 | 3