1

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?

9
  • Does this answer your question? Convert Numpy array of ASCII codes to string Commented Apr 4, 2022 at 12:43
  • Nope............... Commented Apr 4, 2022 at 12:44
  • What's the expected result in your example? Commented Apr 4, 2022 at 12:46
  • To return 16 character long ascii string.. Commented Apr 4, 2022 at 12:47
  • 1
    @GhostCat Will keep it in mind.. THanks Commented Oct 7, 2022 at 12:20

2 Answers 2

0

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

result = ''.join(map(chr, np.packbits(arr)))
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.