Assembly Language for Beginners

(nextflipdebug2) #1

Chapter 3


3 Slightly more advanced examples


3.1 Double negation


A popular way^1 to convert non-zero value into 1 (or booleantrue) and zero value into 0 (or booleanfalse)
is!!statement:


int convert_to_bool(int a)
{
return !!a;
};


Optimizing GCC 5.4 x86:


convert_to_bool:
mov edx, DWORD PTR [esp+4]
xor eax, eax
test edx, edx
setne al
ret


XORalways clears return value inEAX, even in case ifSETNEwill not trigger. I.e.,XORsets default return
value to zero.


If the input value is not equal to zero (-NEsuffix inSETinstruction), 1 is set toAL, otherwiseALisn’t
touched.


WhySETNEoperates on low 8-bit part ofEAXregister? Because the matter is just in the last bit (0 or 1),
while other bits are cleared byXOR.


Therefore, that C/C++ code could be rewritten like this:


int convert_to_bool(int a)
{
if (a!=0)
return 1;
else
return 0;
};


...or even:


int convert_to_bool(int a)
{
if (a)
return 1;
else
return 0;
};


Compilers targetingCPUs lacking instruction similar toSET, in this case, generates branching instructions,
etc.


(^1) This way is also controversial, because it leads to hard-to-read code

Free download pdf