-1

I have multiple arrays, each contain 6 integer values. eg x[0. 1. 0. 2. 1. 2.] i want to convert each value in each array into binary array e.g. x_bin[0,0, 0,1, 0,0, 1,0, 0,1, 1,0]. Note that initially my variable has 6 integer (from 0 - 2), i want my final result to contain 12 values (2 bits for each integer).

Thank you in advance.

Shreta Ghimire
  • 1,019
  • 2
  • 13
  • 27
  • Are the values always 0, 1, or 2? – rassar Oct 03 '19 at 22:45
  • Possible duplicate of [Python int to binary string?](https://stackoverflow.com/questions/699866/python-int-to-binary-string) – chash Oct 03 '19 at 22:46
  • @hmm no not a duplicate, i already checked into what you have shared. It does not work for my case. I want to change the whole array at a time as I have multiple arrays. – Shreta Ghimire Oct 03 '19 at 22:47
  • @rassar yes, they are always, 0, 1 and 2. – Shreta Ghimire Oct 03 '19 at 22:48
  • 1
    It's a duplicate, with a bit of case-specific logic... `['{0:02b}'.format(x) for x in [0, 1, 0, 2, 1, 2]]` will change the entire array to two-bit binary strings. Another pass could split those strings and cast them to int... – chash Oct 03 '19 at 23:02
  • @hmm thanks it is similar to what i am looking for but it will be more beneficial for my work if each character of the binary are separated into two different values eg. for ```2``` i want ```1,0``` instead of ```10```. – Shreta Ghimire Oct 03 '19 at 23:51
  • 1
    If you show your attempts to solve the problem, you may receive more specific help. – chash Oct 03 '19 at 23:59

1 Answers1

0

Convert each number to binary, then convert each binary digit to an integer.

>>> x = [0, 1, 0, 2, 1, 2]
>>> [tuple(int(c) for c in '{:02b}'.format(i)) for i in x]
[(0, 0), (0, 1), (0, 0), (1, 0), (0, 1), (1, 0)]
wjandrea
  • 28,235
  • 9
  • 60
  • 81