I have a question. How can I import value like this:
JavaScript
x
2
1
value = 0b1010
2
to an array like this:
JavaScript
1
2
1
array = np.array([1, 0, 1, 0])
2
and vice versa?
Advertisement
Answer
np.binary_repr
function turn integers into binary representation string, so you could do:
JavaScript
1
5
1
import numpy as np
2
value = 0b1010
3
arr = np.array(list(np.binary_repr(value)),dtype=int)
4
print(arr)
5
Output:
JavaScript
1
2
1
[1 0 1 0]
2
Reverse direction (as requested by @sai):
JavaScript
1
4
1
arr = np.array([1,0,1,0],dtype=int)
2
value = np.sum(arr * [2**i for i in reversed(range(len(arr)))])
3
print(value)
4
Output:
JavaScript
1
2
1
10
2
Explanation: I build list
with desceding powers of 2
(in this case [8,4,2,1]) using list
comprehension then multiply arr
(i.e. multiply pairwise elements from arr
and said list
) then np.sum
.