0

How can I limit the resuly to only 8 bits? I have to add two binary numbers and convert the result to decimal. How to limit the sum to only 8 bits or 255?

def BinaryToDecimal(binaryNum):
    binaryList = []
    decimalNumber = 0

    while binaryNum != 0:
            remainder = binaryNum%10
            binaryList.append(remainder)
            binaryNum = int(binaryNum/10)

    for i in range(len(binaryList)-1,-1,-1):
        decimalNumber = decimalNumber + binaryList[i] * (2**i)

    return decimalnumber
David Buck
  • 3,752
  • 35
  • 31
  • 35
Sank2058
  • 1
  • 2

2 Answers2

0

Assuming you want the last 8 bits of your result, the simple solution is just to use modular arithmetic and use % 256 to get the remainder after dividing by 256.

def BinaryToDecimal(binaryNum):
    binaryList = []
    decimalNumber = 0

    while binaryNum != 0:
        remainder = binaryNum % 10
        binaryList.append(remainder)
        binaryNum = int(binaryNum / 10)

    for i in range(len(binaryList) - 1, -1, -1):
        decimalNumber = decimalNumber + binaryList[i] * (2 ** i) 

    return decimalNumber % 256 # You also had a typo in this line

For example:

BinaryToDecimal(11111100000000)
Out[1]: 0
BinaryToDecimal(11111111111111)
Out[2]: 255

Alternatively, if you want to return 255 if the answer is > 255, the code would be:

return decimalNumber if decimalNumber < 256 else 255

This returns:

BinaryToDecimal(10000000)
Out[3]: 128
BinaryToDecimal(100000000)
Out[4]: 255
BinaryToDecimal(1000000000000)
Out[5]: 255

Incidentally: I fixed a typo in the return statement and your variable names don't conform to the PEP-8 Python styles - variables should be in lower case separated by underscores like binary_num and decimal_number

David Buck
  • 3,752
  • 35
  • 31
  • 35
0

I have written a function for you:

def bin_to_dec(bits,fmt = None):
    if bits != 0:
        bits = str(bits)
        if fmt == 'big':
            bits = bits[:8]
        else:
            bits = bits[-8:]
        try:
            return int(bits,2)
        except ValueError:
            print("Enter bits only no number other than 1 and 0!!!")
    return 0

and on doing this:

>>> print(bin_to_dec(11111111110000,'big'))
255
>>> print(bin_to_dec(11111111110000,'little'))
240

Just pass your binary as int, if you have it as string than you can remove bits = str(bits) line from my code. fmt is for data format for little or big endian depends on you. To understand Little and Big Endian Check Here. Default is little and on any error it will always return 0.

Example if you gave anything other than 1 or 0 in bits:

>>> print(bin_to_dec(11111112110000,'little'))
Enter bits only no number other than 1 and 0!!!
0

You will get 0 and a bonus print output

JenilDave
  • 606
  • 6
  • 14