1

My question is related to this stackoverflow post: enter link description here, in which inspectorG4dget provided the code

def decToBin(n):
    if n==0: return ''
    else:
        return decToBin(n/2) + str(n%2)

which recursion Alex Martelli observed was unnecessary, since the obvious bin(x)[2:] could be used. This is fine if the user needs the binary representation as a string. However, I need the binary representation as a list or numpy ndarray. As I can see, my options are a) adaptation of this code or b) something like this string.split(','.join(bin(10)[2:]),','). I know string operations tend to be expensive, but recursion can also be expensive.

Given that I need to convert an integer into an array_like of bits, which option (a or b) is likely to be more efficient? Is there another simpler & better way completely?

Community
  • 1
  • 1
Dr. Andrew
  • 2,532
  • 3
  • 26
  • 42

1 Answers1

6

You can simply convert a string to list by list().

list(bin(10)[2:])
Janne Karila
  • 24,266
  • 6
  • 53
  • 94
  • Ah so simple. Though I swear I tried that initially, and it gave me a list with 1 element ['1010']. Now I'm ashamed to have this question even here :-). – Dr. Andrew Oct 18 '12 at 06:39