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.
bin(), right?int8/16/32/64 with float/negative ? need read moreIEEE