Home > Software design >  How to convert numpy.int8 to string?
How to convert numpy.int8 to string?

Time:04-05

The below code tries to get ascii code from a 128 bit long numpy array.

st=""
ans_final=""

for i in range(len(key)):
  j=0
  while(j<8):
    st=st  (key[i])
    j =1
    i =1
  ans=b_to_ascii(st)
  ans_final=ans_final ans

In this code I am planning to pass a string of 8 bit long to b_to_ascii function which will return the ascii value of it, and then append all the ascii values together to get a string of 8 ascii values stored in ans_final.

But I am getting this error

TypeError                                 Traceback (most recent call last)
<ipython-input-30-5929c83ea390> in <module>()
      6   j=0
      7   while(j<8):
----> 8     st=st  (key[i])
      9     j =1
     10     i =1

TypeError: can only concatenate str (not "numpy.int8") to str

Say the key here is stored like this-->

array([1,1,0,0,0,0,1,0,1,1,0,0,0,1,0,0,1,1,0,0,0,1,1], dtype=int8)

So after conversion to ascii the final answer will be abc.

In the first iteration of the code, what I want to do is, I want a string st=11000010 passed to the function b_to_ascii which will return a which will get stored in ans and will be appended to the string ans_final. Similarly we will iterate the next 8 bits and remaining 8 bits to get b and c so the ans_final will become abc

So can anyone help me with how can I convert NumPy.int8 to string?

CodePudding user response:

You can use the numpy.packbits function (arr is your array of bits):

result = ''.join(map(chr, np.packbits(arr)))

CodePudding user response:

Maybe string conversion in a comprehension, then str.join() method :

for i in range(0, len(key), 8):
    s = ''.join(str(nbr) for nbr in key[i:i 8])
    ans = b_to_ascii(s)
  • Related