multiply.cc

来自「一个mips虚拟机非常好代码,使用C++来编写的,希望大家多学学,」· CC 代码 · 共 90 行

CC
90
字号
#include "inttypes.hh"// Perform long multiplication of x by y.template <> MulResult<UInt64>multiply(UInt64 u, UInt64 v){    UInt64 u0 = bits(u, 31,  0);    UInt64 u1 = bits(u, 63, 32);    UInt64 v0 = bits(v, 31,  0);    UInt64 v1 = bits(v, 63, 32);    UInt64 w0 = 0;    UInt64 w1 = 0;    UInt64 w2;    UInt64 w3;    UInt64 t, k;    k = 0;    // i == 0, j == 0    t  = u0 * v0 + w0 + k;    w0 = bits(t, 31,  0);    k  = bits(t, 63, 32);    // i == 1, j == 0    t  = u1 * v0 + w1 + k;    w1 = bits(t, 31,  0);    k  = bits(t, 63, 32);    w2 = k;    k  = 0;    // i == 0, j == 1    t  = u0 * v1 + w1 + k;    w1 = bits(t, 31,  0);    k  = bits(t, 63, 32);    // j == 1, i == 1    t  = u1 * v1 + w2 + k;    w2 = bits(t, 31,  0);    k  = bits(t, 63, 32);    w3 = k;    // Glue the bits back into full words.    UInt64 lo = w0 | (w1 << 32);    UInt64 hi = w2 | (w3 << 32);    return MulResult<UInt64>(hi, lo);}template <> MulResult<Int64>multiply(Int64 u, Int64 v){    // Compute the sign of the result;    bool neg;    if (u < 0) {	if (v < 0) {	    neg = false;	    v = -v;	}	else {	    neg = true;	}	u = -u;    }    else {	if (v < 0) {	    neg = true;	    v = -v;	}	else {	    neg = false;	}    }    MulResult<UInt64> ret = multiply((UInt64)u, (UInt64)v);    if (neg) {	ret.lo = ~ret.lo;	ret.hi = ~ret.hi;	if (++ret.lo == 0) {	    ++ret.hi;	}    }    return MulResult<Int64>(ret.hi, ret.lo);}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?