This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the l
def trans(x):
if x == 0: return [0]
bit = []
while x:
bit.append(x % 2)
x >>= 1
return bit[::-1]
In most cases you want your binary number to be a specific length. For example you want 1 to be 8 binary digits long [0,0,0,0,0,0,0,1]. I use this myself:
def convert_to_binary(num, length=8):
binary_string_list = list(format(num, '0{}b'.format(length)))
return [int(digit) for digit in binary_string_list]
# dec2bin.py
# FB - 201012057
import math
def dec2bin(f):
if f >= 1:
g = int(math.log(f, 2))
else:
g = -1
h = g + 1
ig = math.pow(2, g)
st = ""
while f > 0 or ig >= 1:
if f < 1:
if len(st[h:]) >= 10: # 10 fractional digits max
break
if f >= ig:
st += "1"
f -= ig
else:
st += "0"
ig /= 2
st = st[:h] + "." + st[h:]
return st
# MAIN
while True:
f = float(raw_input("Enter decimal number >0: "))
if f <= 0: break
print "Binary #: ", dec2bin(f)
print "bin(int(f)): ", bin(int(f)) # for comparison
You can first use the format function to get a binary string like your current function. For e.g the following snippet creates a binary string of 8 bits corresponding to integer 58.
>>>u = format(58, "08b")
'00111010'
Now iterate the string to convert each bit to an int to get your desired list of bits encoded as integers.
>>>[int(d) for d in u]
[0, 0, 1, 1, 1, 0, 1, 0]
This will do it. No sense in rolling your own function if there's a builtin.
def binary(x):
return [int(i) for i in bin(x)[2:]]
The bin()
function converts to a string in binary. Strip of the 0b
and you're set.
Converting decimal to binary is a matter of how you are going to use the % and //
def getbin(num):
if (num==0):
k=[0]
return k
else:
s = []
while(num):
s.append(num%2)
num=num//2
return s