1

I have a binary np array below:

arr = [0. 0. 1. ... 0. 1. 1.]

I would like to convert them to the binary sequences stored as its ascii value of each element to a .bin file (the output file name is 'test.bin'). For example, zero's ascii value is 48 and its corresponding binary form is: 00110000. If there is a zero in the np array, there should be a corresponding 00110000 in the bin file I tried to use the code below:

buffer_string = ''.join(str(x) for x in arr.astype(int))
with open("test.bin", "wb") as f:
    for x in buffer_string:
        f.write(bytes(ord(x)))

But the outputs are all zeros. Could you please give me some suggestions?

Thanks

7
  • What exactly should be the resulting contents of the file in this example? Commented Jul 12, 2020 at 1:07
  • For example, zero's ascii value is 48 and its corresponding binary form is: 00110000. If there is a zero in the np array, there should be a corresponding 00110000 in the bin file Commented Jul 12, 2020 at 1:09
  • Did you try f.write(buffer_string)? Commented Jul 12, 2020 at 1:11
  • Sure I tried. But I got the following error: TypeError: a bytes-like object is required, not 'str' Commented Jul 12, 2020 at 1:12
  • Then you either need to open the file with 'w', or explicitly encode the string as ASCII. I don't think it makes a difference in this case (since '0' and '1' have the same encoding in ASCII and UTF-8 afaik). Commented Jul 12, 2020 at 1:14

0

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.