In: Computer Science
This is using Python, it is utilizing code from a Fraction class to create a Binary Class Please leave comments so I may be able to learn from this.
Instruction for Binary Class:
Exercise 6.18: Design an immutable class BinaryNumber, in the
style of our Fraction
class. Internally, your only instance variable should be a text
string that represents
the binary value, of the form '1110100'. Implement a constructor
that takes a
string parameter that specifies the original binary value. Provide
natural implemen-tations for the special methods __add__, __sub__,
__lt__, __gt__, __eq__,__str__, and __int__. Note: with the
exception of __int__, you are not to con-vert the internal values
back to integers when implementing the operations; perform the
arithmetic directly upon the internal binary representations.
Code from Fraction class:
from gcd import gcd
class Fraction:
def __init__(self, numerator=0, denominator=1):
if denominator == 0: # fraction is undefined
self._numer = 0
self._denom = 0
else:
factor = gcd( abs(numerator), abs(denominator) )
if denominator < 0: # want to divide through by negated
factor
factor = -factor
self._numer = numerator // factor
self._denom = denominator // factor
######## Arithmetic Methods ########
def __add__(self, other):
return Fraction(self._numer * other._denom + other._numer *
self._denom, self._denom * other._denom)
def __sub__(self, other):
return Fraction(self._numer * other._denom - other._numer *
self._denom, self._denom * other._denom)
def __mul__(self, other):
return Fraction(self._numer * other._numer, self._denom *
other._denom)
def __truediv__(self, other): # multiplication by
reciprocal
return Fraction(self._numer*other._denom,
self._denom*other._numer)
######## Comparison Methods ########
def __lt__(self, other):
return self._numer * other._denom < self._denom *
other._numer
  
def __eq__(self, other):
if self._numer == other._numer and self._denom ==
other._denom:
return True
else:
return False
######## Type Conversion Methods ########
def __float__(self):
return float(self._numer) / self._denom
def __int__(self):
return int(float(self)) # convert to float, then truncate
  
def __str__(self):
if self._denom == 0:
return 'Undefined'
elif self._denom == 1:
return str(self._numer)
else:
return str(self._numer) + '/' + str(self._denom)
class BinaryNumber:
    def __init__(self, binary):
        self._bina = binary
    
    def normaliseString(str1,str2):
        diff = abs((len(str1) - len(str2)))
        if diff != 0:
            if len(str1) < len(str2):
                str1 = ('0' * diff) + str1
            
            else:
                str2 = ('0' * diff) + str2
           
        return [str1,str2]
    def __add__(self,other):
        x,y=self._bina,other._bina
        maxlen = max(len(x), len(x))
        
        #Normalize lengths
        x = x.zfill(maxlen)
        y = y.zfill(maxlen)
        result = ''
        carry = 0
        for i in range(maxlen-1, -1, -1):
            r = carry
            r += 1 if x[i] == '1' else 0
            r += 1 if y[i] == '1' else 0
            # r can be 0,1,2,3 (carry + x[i] + y[i])
            # and among these, for r==1 and r==3 you will have result bit = 1
            # for r==2 and r==3 you will have carry = 1
            result = ('1' if r % 2 == 1 else '0') + result
            carry = 0 if r < 2 else 1       
        if carry !=0 : result = '1' + result
        return BinaryNumber(result.zfill(maxlen))
    def __sub__(self,other):
        str1,str2=self._bina,other._bina
        if len(str1) == 0:
            return
        if len(str2) == 0:
            return 
        str1,str2 = normaliseString(str1,str2)
        startIdx = 0
        endIdx = len(str1) - 1
        carry = [0] * len(str1)
        result = ''
        
        while endIdx >= startIdx:
            x = int(str1[endIdx])
            y = int(str2[endIdx])
            if carry[endIdx]==-1 and x==0:
                sub=0
                carry[endIdx-1]=-1
            else:
                sub = (carry[endIdx] + x) - y
            
            if sub == -1:
                result += '1'
                carry[endIdx-1] = -1
            elif sub == 1:
                result += '1'
            elif sub == 0:
                result += '0'
            
            else:
                raise Exception('Error')
            endIdx -= 1
   
        return BinaryNumber(result[::-1])
    def __eq__(self,other):
        if self._bina^other._bina==0
            return True
    def __int__(self):
        binary = int(self._bina)
        decimal, i, n = 0, 0, 0
        while(binary != 0): 
            dec = binary % 10
            decimal = decimal + dec * pow(2, i) 
            binary = binary//10
            i += 1
        return decimal
    def __str__(self):
        return self._bina
    def __lt__(self,other):
        str1 = self._bina
        str2 = other._bina
        tot1,tot2,lent,power=0,0,len(str1)-1,0
        str1,str2 = normaliseString(str1,str2)
        for i in range(len(str1)):
            tot1+=int(str1[lent]) * pow(2,power)
            tot2+=int(str2[lent]) * pow(2,power)
            power+=1
            lent-=1
        if tot1>tot2:
            return False
        else:
            return True
            
    def __lt__(self,other):
        str1 = self._bina
        str2 = other._bina
        tot1,tot2,lent,power=0,0,len(str1)-1,0
        str1,str2 = normaliseString(str1,str2)
        for i in range(len(str1)):
            tot1+=int(str1[lent]) * pow(2,power)
            tot2+=int(str2[lent]) * pow(2,power)
            power+=1
            lent-=1
        if tot1>tot2:
            return True
        else:
            return False