Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assembly to compare two numbers

What is the assembler syntax to determine which of two numbers is greater?

What is the lower level (machine code) for it? Can we go even lower? Once we get to the bit level, what happens? How is it represented in 0's and 1's?

like image 962
Alex Gordon Avatar asked Jul 14 '09 04:07

Alex Gordon


People also ask

Which operation is used when a programmer wants to compare two numbers in assembly language?

As already mentioned, usually the comparison is done through subtraction.

What is comparison in assembly language?

In assembly, all branching is done using two types of instruction: A compare instruction, like "cmp", compares two values. Internally, it does this by subtracting them. A conditional jump instruction, like "je" (jump-if-equal), does a goto somewhere if the two values satisfy the right condition.

What does cmp do in assembly?

The CMP instruction compares two operands. It is generally used in conditional execution. This instruction basically subtracts one operand from the other for comparing whether the operands are equal or not. It does not disturb the destination or source operands.


2 Answers

In TASM (x86 assembly) it can look like this:

cmp BL, BH
je EQUAL       ; BL = BH
jg GREATER     ; BL > BH
jmp LESS       ; BL < BH

in this case it compares two 8bit numbers that we temporarily store in the higher and the lower part of the register B. Alternatively you might also consider using jbe (if BL <= BH) or jge/jae (if BL >= BH).

Hopefully someone finds it helpful :)

like image 103
LihO Avatar answered Sep 19 '22 15:09

LihO


First a CMP (comparison) instruction is called then one of the following:

jle - jump to line if less than or equal to
jge - jump to line if greater than or equal to

The lowest assembler works with is bytes, not bits (directly anyway). If you want to know about bit logic you'll need to take a look at circuit design.

like image 30
Spencer Ruport Avatar answered Sep 18 '22 15:09

Spencer Ruport