Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most compact way to test for a negative number in x86 assembly?

Tags:

x86

assembly

Currently I am doing this to test for a negative number in x86 assembly (r/m32,imm8):

83F800 CMP EAX, 0

This can be followed by JL. This is 3 bytes and supposedly clocks at "1/2". I could use TEST EAX, or CMP EAX,imm32 (encoding 3D), both of which clock at "1", but take 5 bytes. In general, if I am trying to minimize code size, is the way I am doing it correct? Once again, this is to test if a number is less than zero.

like image 949
Tyler Durden Avatar asked Mar 16 '13 19:03

Tyler Durden


People also ask

How do you show negative numbers in assembly?

Negative numbers are represented in Two's Complement in assembly. In order to obtain Two's Complement of a number you have two options: to complement all it's bits and add one. to complement all it's bits until the last 1.

What does lea do x86?

The lea instruction places the address specified by its first operand into the register specified by its second operand. Note, the contents of the memory location are not loaded, only the effective address is computed and placed into the register.

What does test do in x86 assembly?

In the x86 assembly language, the TEST instruction performs a bitwise AND on two operands. The flags SF , ZF , PF are modified while the result of the AND is discarded. The OF and CF flags are set to 0 , while AF flag is undefined.


2 Answers

add eax, eax is only two bytes (01 C0 or 03 C0), but destructive. (check for carry afterwards)

test eax, eax is also only two bytes (85 C0). (check for sign afterwards)

like image 92
harold Avatar answered Oct 18 '22 17:10

harold


You can use:

or      eax, eax

it is one byte shorter (only two bytes op code) instruction!

like image 36
GJ. Avatar answered Oct 18 '22 16:10

GJ.