xorpd assembly riddle 0x02

Syscall59 — Alan Vivona
syscall59
Published in
3 min readNov 19, 2018

--

xorpd has some riddle-like pieces of assembly code here. In this post, I’ll analyze this one.

I present to you the riddle number 0x02:

neg      rax
sbb rax,rax
neg rax

In order to understand this one we first need to understand neg and sbb instructions. Let’s check Intel’s manuals:

Integer Subtraction with Borrow (aka sbb) definition from Intel’s manual:

Adds the source operand (second operand) and the carry (CF) flag, and subtracts the result from the destination operand (first operand). The result of the subtraction is stored in the destination operand

DEST ← (DEST — (SRC + CF));

Two’s Complement Negation (aka neg) definition from Intel’s manual:

Replaces the value of operand (the destination operand) with its two’s complement. (This operation is equivalent to subtracting the operand from 0.)

IF DEST = 0 
THEN CF ← 0;
ELSE CF ← 1;
FI;
DEST ← [– (DEST)]

Now you may ask, how’s the two’s complement obtained? It’s obtained just by flipping every bit and then adding 1 to the result. Here are some examples:

00110101 ==(flip)==> 11001010 ==(+1)==> 11001011 
11001011 is the 2’s complement of 00110101

--

--