From a675f1613f8b0c375eb3cbbe7ae35a9d3de1c303 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beno=C3=AEt=20Allard?= Date: Thu, 22 Sep 2011 23:33:03 +0200 Subject: [PATCH] More methods for the BigNumber class --- pythoncardx/framework/math.py | 49 ++++++++++++++++++++++++++++++----- 1 file changed, 43 insertions(+), 6 deletions(-) diff --git a/pythoncardx/framework/math.py b/pythoncardx/framework/math.py index 57d6bc5..4423722 100644 --- a/pythoncardx/framework/math.py +++ b/pythoncardx/framework/math.py @@ -1,4 +1,5 @@ from python.lang import NullPointerException, ArithmeticException +from pythoncard.framework import Util def from_bcd(data): """ @@ -7,19 +8,29 @@ def from_bcd(data): """ return int(hex(data)[2:]) +def to_bcd(data): + """ + >>> to_bcd(59) + 0x59 + """ + a = data // 10 + b = data % 10 + return (a << 4) + b + def from_hex(data): """ >>> from_hex(0x59) 786 """ return data +to_hex = from_hex class BigNumber(object): FORMAT_BCD = 1 FORMAT_HEX = 2 - def __init__(self, maxBytes): - if maxBytes <= 0: + def __init__(self, maxBytes = None): + if maxBytes is not None and maxBytes <= 0: raise ArithmeticException() self.maxBytes = maxBytes self._value = None @@ -27,8 +38,6 @@ def __init__(self, maxBytes): def init(self, bArray, bOff, bLen, arrayFormat): if bLen == 0: raise ArithmeticException() - if arrayFormat not in (self.FORMAT_BCD, self.FORMAT_HEX): - raise ArithmeticException() if bArray is None: raise NullPointerException() if arrayFormat == self.FORMAT_BCD: @@ -40,7 +49,9 @@ def init(self, bArray, bOff, bLen, arrayFormat): self._value = 0 for i in xrange(bLen): self._value = self._value << 8 - self._value += bArray[bOff+i] + self._value += from_hex(bArray[bOff+i]) + else: + raise ArithmeticException @staticmethod def getMaxBytesSupported(): @@ -48,10 +59,15 @@ def getMaxBytesSupported(): return 20 def multiply(self, bArray, bOff, bLen, arrayFormat): - other = BigNumber(70) + other = BigNumber() other.init(bArray, bOff, bLen, arrayFormat) self._value *= other._value + def subtract(self, bArray, bOff, bLen, arrayFormat): + other = BigNumber() + other.init(bArray, bOff, bLen, arrayFormat) + self._value -= other._value + def compareTo(self, operand): if self._value == operand._value: return 0 @@ -59,3 +75,24 @@ def compareTo(self, operand): return 1 else: return -1 + + def toBytes(self, outBuf, bOff, numBytes, arrayFormat): + array = [] + if arrayFormat == self.FORMAT_BCD: + value = self._value + while value > 100: + array.append(to_bcd(value % 100)) + value = value // 100 + elif arrayFormat == self.FORMAT_HEX: + value = self._value + while value > 0xff: + array.append(to_hex(value % 0xff)) + value = value // 0xff + else: + raise ArithmeticException + if numBytes < len(array): + raise ArithmeticException + array.extend([0 for i in range(numBytes - len(array))]) + array.reverse() + Util.arrayCopy(array, 0, outBuf, bOff, numBytes) +