I have a binary string representation of a byte, such as
01010101
How can I convert it to a real binary value and write it to a binary file?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use the
intfunction with abaseof2to read a binary value as an integer.Python 2 uses strings to handle binary data, so you would use the
chr()function to convert the integer to a one-byte string.Python 3 handles binary and text differently, so you need to use the
bytestype instead. This doesn’t have a direct equivalent to thechr()function, but thebytesconstructor can take a list of byte values. We putnin a one element array and convert that to abytesobject.Once you have your binary string, you can open a file in binary mode and write the data to it like this: