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?
-
1this would work also: [c for c in bin(10)[2:]] or map(None, bin(10)[2:])andrean– andrean2012年10月18日 06:28:13 +00:00Commented Oct 18, 2012 at 6:28
1 Answer 1
You can simply convert a string to list by list().
list(bin(10)[2:])
1 Comment
Explore related questions
See similar questions with these tags.