public static BCD operator -(BCD l, BCD r) { try { int maxLen = Math.Max(l.Length, r.Length); l.MaxLen = maxLen; r.MaxLen = maxLen; if (l.Sign < 0) { if (r.Sign < 0) { BCD a = Abs(l) + Abs(r); a.SetSign(-1); return(a); } else { return(r + Abs(l)); } } else { if (r.Sign < 0) { return(l + Abs(r)); } else { BCD ret = BCD.Zero; ret.MaxLen = maxLen; if (l > r) { int carry = 0; for (int i = maxLen - 1; i >= 0; i--) { Once a = l[i] - r[i]; a.ValueSub(Math.Abs(carry)); ret[i] = a; carry = a.Carry; } if (carry != 0) { ret[0].ValueSub(Math.Abs(carry)); } return(ret); } else { if (l == r) { return(BCD.Zero); } BCD a = r - l; a.SetSign(-1); return(a); } } } } catch (Exception ex) { throw new BCDException("operator - error.", l, r, ex); } }
public static BCD operator *(BCD l, BCD r) { try { int maxLen = Math.Max(l.Length, r.Length); l.BCDbyteValue.VirtualCount = maxLen; r.BCDbyteValue.VirtualCount = maxLen; if (l.Sign < 0) { if (r.Sign < 0) { return(Abs(l) * Abs(r)); } else { BCD a, b, c; b = Abs(l); c = Abs(r); a = b * c; a.SetSign(-1); return(a); } } else { if (r.Sign < 0) { BCD a, b, c; b = Abs(l); c = Abs(r); a = b * c; a.SetSign(-1); return(a); } else { if (IsZero(l) || IsZero(r)) { return(new BCD()); } BCD gre = l > r ? l : r; if (gre != l) { r = l; l = gre; } BCD ans = new BCD(); IEnumerator <Once> re = r.BCDbyteValue.GetReverseEnumerator(); int digit = 0; while (re.MoveNext()) { BCD m1 = new BCD { MaxLen = maxLen }; int carry = 0; int idx = maxLen - 1; Once m = re.Current; if (m.Val == Once.Zero.Val) { digit++; continue; } IEnumerator <Once> le = l.BCDbyteValue.GetReverseEnumerator(); while (le.MoveNext()) { Once a = le.Current * m; a.ValueAdd(carry); m1[idx--] = a; carry = a.Carry; } if (carry > 0) { if (idx >= 0) { m1[idx] = new Once() { Val = (byte)carry }; } else { m1.BCDbyteValue.Insert(0, new Once() { Val = (byte)carry }); } } if (!BCD.IsZero(m1)) { BCD tmp = Multiply10(m1, digit++); ans += tmp; } } return(ans); } } } catch (Exception ex) { throw new BCDException("operator * error.", l, r, ex); } }
public static BCD operator +(BCD l, BCD r) { try { int maxLen = Math.Max(l.Length, r.Length); l.MaxLen = maxLen; r.MaxLen = maxLen; if (l.Sign < 0) { if (r.Sign < 0) { BCD a = Abs(l) + Abs(r); a.SetSign(-1); return(a); } else { BCD a, b, c; b = Abs(l); c = Abs(r); if (b == c) { return(new BCD()); } if (b > c) { a = b - c; a.SetSign(l.Sign); } else { a = c - b; a.SetSign(r.Sign); } return(a); } } else { if (r.Sign < 0) { BCD newR = Abs(r); return(l - newR); } else { BCD ret = new BCD { MaxLen = maxLen }; int carry = 0; for (int i = maxLen - 1; i >= 0; i--) { Once a = l[i] + r[i]; a.ValueAdd(carry); ret[i] = a; carry = a.Carry; } if (carry > 0) { ret.MaxLen++; ret[0] = new Once() { Val = (byte)carry }; } return(ret); } } } catch (Exception ex) { throw new BCDException("operator + error.", l, r, ex); } }