How a processor can calculate if A < B
This is probably a dumb question came to my mind, but I think I don't have answer to this -
How processor would find if A < B? In fact there are other things as well like A>B or A==B.
But if we solve A
I understand that different processors may probably have different implementations but I wanted to have some high level idea of doing this.
Some tri开发者_如何学运维ck with bitwise operators should do it, I believe.
Any help would be greatly appreciated.
In x86 assembly, the CMP instruction is often used to compare two integers.
For instance, if you have integers in EAX and EBX respectively, and do CMP EAX,EBX, the values of the sign (S) flag and the zero (Z) flag will tell you which number was largest:
EAX > EBX: Z=0, S=0
EAX == EBX: Z=1, S=0
EAX < EBX: Z=0, S=1
The same result can be obtained by using the SUB instruction, which also stores the difference between the numbers in the destination register.
Subtract B
from A
and see if the N
(negative) flag or the MSb of the result is set.
All CPUs have ALUs. I won't post Wikipedia links as you are good enough to find by yourself ;) but I can teach you a bit about CPU's internal.
What you basically need to know is that all CPUs have comparison instructions, ie BEQ "Branch-on-Equal" which is used to implement "if" instructions and jumps if A == B (there is another instruction for A < B, etc). When CPU reads this instruction and the operands, it loads them in the two ALU input buses and sets a proper ALU code that represents the comparison operation. The ALU is built to compare the numbers via hardware and output a proper result on its output side, or setting a status bit on the CPU.
Hardware comparison of numbers is easy, and almost all academic student have once designed a comparison (from 4 to 8 bits, but same logic applies to 32 and 64), you can find schematics anywhere
精彩评论