Python binary file to array
If you're using Python 3. But in Python 2. As usual, showing with the interactive interpreter is easier than explaining with text, so let me just do that. Use struct. The benefit of this method is that it works for other types as well, for example if any of the values were greater than you could use '5i' for the format instead to get full bit integers.
As of Python 3. You can also shorten the last two lines into a single one:. So you're looking at doing the following. How are we doing? Please help us improve Stack Overflow. Take our short survey.
Stack Overflow for Teams — Collaborate and share knowledge with a private group. Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Python how to write to a binary file? Ask Question. Asked 8 years, 4 months ago. Active 7 months ago. On linux you should open this with something like Vim. Gedit would simply struggle to open large files.
I am attaching the raw version of this file that you use for yourself. Further in the article I shall tell you how to generate a raw binary for yourself. Finally, I ended up with a. Now, for any C array to be usable, it needs to have some name. Correspondingly, I modified my writing function to add some static content that creates a C array.
This should look like a C array definition. Furthermore, the len data also computes the size of the array. Finally, we are nearing the end of it. We are still not done yet. If we look at the file, it would be one long array that goes for miles beyond the screen.
Stack Exchange to the rescue, I found a code snippet that does the formatting for us. This piece of code is responsible for adding new line after every 66 characters. You could have any number of characters. For example, 72, 36 also looks nicely aligned. As shown in the output. To get the output, I have used print number. And to close the file, I have used file. In the below screenshot you can see the output. To read the byte from the file, I have used print byte.
You can refer to the below screenshot for the output. Improve this question. David Ferris David Ferris 1, 4 4 gold badges 24 24 silver badges 43 43 bronze badges. Add a comment. Active Oldest Votes. Improve this answer. Sign up or log in Sign up using Google. Sign up using Facebook. Sign up using Email and Password.
Post as a guest Name. Email Required, but never shown.
0コメント