这是一个基本问题,但是我想将3个数字相乘,这些数字在寄存器$ t2,$ t3和$ t4中。假设,假设每个寄存器只能保持8位,当我们将这三个数相乘时,结果可能大于8位。如果它大于8位,如果每个寄存器只能保存8位,结果如何存储在寄存器$ t0中?
答案 0 :(得分:2)
Usually CPUs have some kind of an instruction that multiplies two registers and gives a result twice as large, spread across multiple registers. This is necessary to implement extended precision arithmetic.
For example on amd64, to multiply two 64-bit numbers and get a 128-bit result you would do:
mov rax, qword ptr [t2]
mul qword ptr [t3]
; the result is now in rdx : rax
mov qword ptr [result], rax
mov qword ptr [result + 8], rdx
To multipliy three 64-bit numbers and get a 192-bit result you would have to implement extended precision multiplication by multiplying the relevant parts as above and summing them together.
答案 1 :(得分:0)
在该特定情况下,算术单元将设置overflow flag
答案 2 :(得分:0)
Nohow. This is well known arithmetic overflow.
Sometimes you can change the order of operators to avoid such overflow. F.e. instead if (a + b > INT_MAX) ...
you can write if (a > INT_MAX - b) ...
and so on.
Sometimes you should use int64
instead of int32
, or double
instead of float
.
And sometimes you should use big numbers library like GMP.