paul
paul

Reputation:

Microsoft ASM interview question?

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!

Upvotes: 6

Views: 3250

Answers (3)

Michael F
Michael F

Reputation: 40832

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.

Upvotes: 7

rahul
rahul

Reputation: 187020

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

Upvotes: 1

Ringding
Ringding

Reputation: 2856

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.

Upvotes: 4

Related Questions