0

I am implementing 8bit adder in python. Here is the adder function definition:

def add8(a0,a1,a2,a3,a4,a5,a6,a7,b0,b1,b2,b3,b4,b5,b6,b7,c0):

All function parameters are boolean. I have implemented function that converts int into binary:

def intTObin8(num):
    bits = [False]*8
    i = 7
    while num >= 1:
        if num % 2 == 1:
            bits[i] = True
        else:
            bits[i] = False
        i = i - 1
        num /= 2
    print bits
    return [bits[x] for x in range(0,8)]

I want this function to return 8 bits. And to use this two functions as follows:

add8(intTObin8(1),intTObin8(1),0)

So the question is: How to pass 8 parameters using one function?

2 Answers 2

2

One way to do this:

add8(*(intTObin8(1) + intTObin8(1) + [0]))

Which concatenates the lists and then passes it as an argument to add8.

If you a doing this a few times you could put it in another function:

def add8_from_bin8(a,b,c0):
    add8(*(a + b + [c0]))

add8_from_bin8(intTObin8(1), intTObin8(1), 0)
Sign up to request clarification or add additional context in comments.

Comments

2

A couple of things:

You do not take 16 parameters in your add8. You take two list, each of 8 elements, if you want to do it.

Plus, in your intToBin you should use 0 and 1 instead of False and True; you should also check that the number can be expressed with 8 bit (if I call that function with 1000, what does it happen?) and you should name your function following PEP8 : http://www.python.org/dev/peps/pep-0008/

ps are you aware that you can simply do int(num, 2) to convert in base 2?

Having said that, sometimes you can use tuple unpacking to simplify your code:

def f(a, b, c):
   bla bla

l = [arg1, arg2, arg3]
f(l[0], l[1], l[2]) #well it's awful
f(*l) #nice

2 Comments

The thing is add8() is written not by me. So I have to play with the rules they created. And I am noob in python :) Thanks for response
ah ok that makes more sense.. but please tell the writer of add8 to learn python :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.