0

I am trying to display all the binary numbers which are divisible by 5 and I am able to successfully show them. But the output is in decimal format even though I have converted them to base 2 (binary).

My code -

user_input = raw_input("Enter three numbers separated by commas: ")
input_list = user_input.split(',')
decimal_list=[]
binary_list=[]
for i in input_list:
     decimal_list.append(int(i,2))
print decimal_list
for x in decimal_list:
    if x%5==0:
        binary_list.append(int(str(x),10))
print binary_list

My input

0000,0001,0010,0011,0100,0101,0110,0111,1000

Output -

[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 5]

Why do I get [0,5] instead of [0000,0101] ? I did convert them back to binary using (int(str(x),10))

2
  • 1
    because python representation of a list of integers is done in base 10. Commented Feb 23, 2018 at 13:52
  • @AkshayNevrekar How do i convert it to binary then ? Or how do I represent the list in binary format ? Commented Feb 23, 2018 at 13:55

1 Answer 1

1

When you have a list of integers and you use print on it, you're implicitly calling list.__repr__() method on it.

This method creates a string with integer numbers in base 10 separated with commas and wrapped with brackets.

If you want to print in binary, you could create a special list object (inheriting from list) and change the way it's represented:

class BinaryList(list):
    def __repr__(self):
        return "[{}]".format(",".join("0b{:04b}".format(x) for x in self))

user_input = "0000,0001,0010,0011,0100,0101,0110,0111,1000"
input_list = user_input.split(',')
decimal_list=[]
binary_list=BinaryList()   # here we're using our special class
for i in input_list:
     decimal_list.append(int(i,2))
print(decimal_list)
for x in decimal_list:
    if x%5==0:
        binary_list.append(int(str(x),10))
print(binary_list)

that prints:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0b0000,0b0101]

This list is specialized: if you enter strings in it, the __repr__ method will fail because of incompatible format. Also note that I have added the 0b prefix in the representation to be able to copy/paste the result & keep the proper values, and avoid mixing it up with decimals.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.