Read binary string, use as binary string python

Viewed 28

I have a binary string "list" as input and want it to be saved as matrix of binaries which I then can use for logical operations (params coming as sys.argv[x]).

Example:

python3 k n matrix
python3 2 2 1101S101S111S1000

Should become a matrix (2D Array, numpy array, whatever) where I can make XOR, AND etc operations. So something like that:

[[1101, 101], [111, 1000]]

There are heaps of manuals about binaries in the Internet, but none which really fits what I am trying to do here.

1 Answers

You can try the following. Given your string, it seems that S is the delimiter between your binary strings. So split on them and simply reshape using numpy

import numpy as np
n = 2
k = 2
s = '1101S101S111S1000'
tokens = s.split('S')
np.array(tokens).reshape(n,k)

which yields

array([['1101', '101'],
       ['111', '1000']], dtype='<U4')
Related