def _signed_add(self, a, b, c=0) -> int: self._reset() value = a + b + c # self.carry = (value + 2 ** 31) > max_32_bits self.overflow = BinaryUtils.overflow(value) self.carry, value = BinaryUtils.add_2cb(a, b, c) self.overflow = BinaryUtils.overflow_msb(a, b, value) result = self._value_common(value) return result
def _value_common(self, value: int) -> int: value = int(value) self.zero = value == 0 self.negative = BinaryUtils.msb(value) if value > max_32_bits_signed or value < min_32_bits_signed: raise ValueError return value
def _unsigned_add(self, a, b, value: int) -> int: self._reset() self.carry = value > max_32_bits self.negative = BinaryUtils.msb(a) if value > max_32_bits: value = value - max_32_bits return value
def test_add_2cb(): assert BinaryUtils.add_2cb(0, 0) == (False, 0) assert BinaryUtils.add_2cb(0, -1) == (False, -1) assert BinaryUtils.add_2cb(0, min_32_bits_signed) == (False, min_32_bits_signed) assert BinaryUtils.add_2cb(0, max_32_bits_signed) == (False, max_32_bits_signed) assert BinaryUtils.add_2cb(min_32_bits_signed, min_32_bits_signed) == (True, 0) assert BinaryUtils.add_2cb(-1, -1) == (True, -1 -1)
def test_positive(): assert BinaryUtils.to_2cb(0) == '0' * 32 assert BinaryUtils.to_2cb(1) == ('0' * 31 + '1') assert BinaryUtils.to_2cb(max_32_bits_signed) == ('0' + '1' * 31)
def test_msb(): assert BinaryUtils.msb(1) == 0 assert BinaryUtils.msb(0) == 0 assert BinaryUtils.msb(-1) == 1
def test_negation(): assert BinaryUtils.neg('1' * 32) == '0' * 32 assert BinaryUtils.neg('0' * 32) == '1' * 32
def test_negative(): assert BinaryUtils.to_2cb(-1) == ('1' * 32) assert BinaryUtils.to_2cb(min_32_bits_signed) == ('1' + '0' * 31)
def _from_binary(cls, value): if value[0] == '0': return int(value, 2) neg = int(BinaryUtils.neg(value), 2) return -(neg + 1)