0

I'm working on this function that converts an integer to 32 bit binary. It works fine for positive integers, but I haven't been able to figure out how to implement two's compliment into the function for negative integer to binary conversions. I've am currently taking the absolute value of negative integers, converting that value to binary, and then flipping the binary values in the string. I just don't know how to implement two's complement into my code.

Here is what I have:

def intToHexaBin(num):
    binnum=abs(num)
    symdict={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"}
    rlist=[]
    blist=[]
    while(binnum!=0):
        if (binnum%2==0):
            blist.append(str(0))
        else:

            blist.append(str(1))
        binnum//=2
    x = (''.join(blist[::-1]).zfill(32))
    if (num<0):
        '''
        I got as far as reversing the binary values for
        converting a negative number to binary
        '''
        for index, value in enumerate(blist):
            blist[index] = '0'
            if value == '0':
                blist[index] = '1'
            elif value == '1':
                blist[index] = '0'
        #not sure how to implement two's complement from here

    return x

print(intToHexaBin(-12))

I'm trying to avoid using built in python functions, because this function is practice for me to learn how to do various conversions. It's a work in progress.

3
  • 1
    you know there's a builtin function called bin(), right? Commented Feb 23, 2017 at 7:00
  • I know about bin(). I appreciate the tip but I'm trying to do this without builtins so I can learn. Commented Feb 23, 2017 at 7:09
  • int 8/16/32/64 with float/negative ? need read more IEEE Commented Feb 23, 2017 at 7:11

2 Answers 2

2

Well, after inverting the bits you obtained the 1-complement. To get 2-complement you have to "add 1". So you need to implement addition:

def add_a_bit(num_repr):
    for i in range(len(num_repr)):
        if num_repr[i] == '0':
            # 0+1 = 1
            num_repr[i] = '1'
            break
        # 1+1 = 0
        num_repr[i] = '0'
    return num_repr

So after inverting the bits in blist call add_a_bit(blist).

I would in the end write something along the lines of:

def int_to_bin(num):
    num_repr = []
    pos_num = abs(num)
    while pos_num:
        if pos_num % 2 == 0:
            num_repr.append('0')
        else:
            num_repr.append('1')
        pos_num //= 2
    if num < 0:
        num_repr = add_a_bit(invert_bits(num_repr))
    return ''.join(reversed(num_repr))


def invert_bits(num_repr):
    for value in num_repr:
        yield '0' if value == '1' else '1'

Which seems to work:

In [7]: int_to_bin(17), bin(17)
Out[7]: ('10001', '0b10001')

Except for 0:

In [8]: int_to_bin(0), bin(0)
Out[8]: ('', '0b0')

I'll let you find how to fix this little bug.

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

1 Comment

Thank you, I'm going to look over all this now.
0

The simplest solution I see would be something like the following:

def intToHexaBin(num):
    if num < 0:
        return '-' + intToHexaBin(-num)
    # continue code here

The return statement exits the code, ignoring whatever may follow, so in the case that a negative value is passed to the function, it will simply prepend a - to the positive converted answer.

Comments

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.