views:

978

answers:

3

I was looking online through samples of interview questions asked in the past by Microsoft and came across this one:

The following asm block performs a common math function, what is it?

cwd xor ax, dx
sub ax, dx

Can somebody please answer this and explain the answer to me? Thanks!!

Update : okay, so its computes the absolute value. Can somebody please explain step by step how it does this? I.e. explain what gets put in which register in each instruction and the alu operation that is performed on which registers etc..Thanks!

+1  A: 

Finds absolute value

It does only operate on AX/EAX - It destroys a register (DX/EDX) - It can be done faster on Pentium and newer processors The problem is the CWD instruction. To replace CWD, you can use this combination: mov dx,ax sar dx,15 (If 32-bit registers are used, shift with a value of 31 instead.)

cwd- convert word to double word.

xor ax, dx => ax = ax xor dx

rahul
thanks..can you please elaborate on how in fact this finds the absolute value? i.e. by showing what the instructions do step by step (well maybe just the first instruction since I understand the second one)
Dude, it’s ASSEMBLER. It IS step-by-step.
Bombe
+3  A: 

It's the abs function (of ax).

If ax is positive, then dx will become 0, and nothing changes.

If ax is negative, dx will be 0xffff, which results in ax~ax - (-1), which is the well-known method for computing neg in a twos-complement representation.

Ringding
+5  A: 

cwd xor ax, dx

Convert word in AX to double-word in DX:AX. Sign is preserved, value is preserved. So if AX >= 0, DX = 0 and if AX < 0, DX = -1.

XOR does nothing if AX == 0.

If AX < 0, the XOR reverses all bits of AX. Then the SUB adds 1 (or subtracts -1, whatever :P) to AX. This is the way to compute 2's complement of a binary number.

All in all, that sequence of instructions places the absolute value of AX into AX and sets DX according to sign.

Michael Foukarakis