2018年5月27日 星期日

[ Python 常見問題 ] How to convert decimal to binary list in python

Source From Here 
Question 
How do I convert a decimal number into a binary list? For example, how do I change 8 into [1,0,0,0] 

How-To 
Try this: 
>>> list('{0:0b}'.format(8))
['1', '0', '0', '0']

Edit -- Ooops, you wanted integers: 
>>> [int(x) for x in list('{0:0b}'.format(8))]
[1, 0, 0, 0]
>>> map(int, list('{0:0b}'.format(8)))
[1, 0, 0, 0]

Or you can do it this way: 
  1. def i2b(x):  
  2.     if x == 0return [0]  
  3.     bit = []  
  4.     while x:  
  5.         bit.append(x % 2)  
  6.         x >>= 1  
  7.     return bit[::-1]  


Supplement 
Convert an integer to binary without using the built-in bin function 

沒有留言:

張貼留言

[ Python 常見問題 ] How to shift a datetime object by 12 hours in python

Source From   Here   Question   Datetime   objects hurt my head for some reason. I am writing to figure out   how to shift a date time obje...