How to emulate 4-bit integer in Python 3?

前端 未结 3 1867
挽巷
挽巷 2021-01-24 09:24

I\'d like to emulate overflow behavior of unsigned 4-bit integers, like this:

>>> x, y = Int4(10), Int4(9)
>>> x + y
Int4(3)
>>> x * y         


        
3条回答
  •  不思量自难忘°
    2021-01-24 10:30

    Overriding the __add__ method is a good idea, because you can make your calculations look clearly. Int4(4) + Int4(7) looks better than Int4(4).addTo(Int4(7)) (or something like this). Here is the code that could help you:

    class Int4:
      def __init__(self, num): # initialising
        self.num = self.cap(num)
    
      def __str__(self):
        return str(self.num)
    
      def __repr__(self):
        return "Int4(" + self.__str__() + ")"
    
      def __add__(self, other): # addition
        return Int4(self.cap(self.num + other.num))
    
      def __sub__(self, other): # subtraction
        return Int4(self.cap(self.num - other.num))
    
      @staticmethod
      def cap(num): # a method that handles an overflow
        while num < 0:
          num += 16
        while num >= 16:
          num -= 16
        return num
    

    And testing it:

    >>> x,y,z = Int4(5), Int4(8), Int4(12)
    >>> x
    Int4(5)
    >>> y
    Int4(8)
    >>> z
    Int4(12)
    >>> print x+y
    13
    >>> print z+y
    4
    >>> print x-z
    9
    

提交回复
热议问题