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?

1
  • 1
    this would work also: [c for c in bin(10)[2:]] or map(None, bin(10)[2:]) Commented Oct 18, 2012 at 6:28

1 Answer 1

6

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

list(bin(10)[2:])
Sign up to request clarification or add additional context in comments.

1 Comment

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 :-).

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.