Python Binary String to ASCII String – and Vice Versa

Problem Formulation In this article, you’ll learn how to convert binary string (values) to an ASCII string in Python. For example, you may want to convert the binary string: 0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100 to the ASCII text: hello world Using a simple Python script! πŸ’¬ Question: How would we write Python code to perform the binary to ASCII … Read more

Python Convert Hex to Base64

πŸ’¬ Question: How to convert a hexadecimal string such as 02af01ff00 to a normal string using the Base64 format in Python? πŸ‘‰ Short answer: Use the following fancy one-liner expression to convert the hex string s to a Base64-encoded Python string: base64.b64encode(bytes.fromhex(s)).decode(). For the long answer, keep reading! πŸ₯Έ If you’re like me, you may … Read more

How to Write to a Binary File in Python?

Problem Formulation πŸ’¬ Question: Given a binary string in your Python script, such as b’this is a binary string’. How to write the binary string to a file in Python? For example, you may have tried a code snippet like this that will not work with file.write(): Because this yields a TypeError: Traceback (most recent … Read more

How to Write a Hex String as Binary Data & Binary File in Python?

Hex String as Binary Data To convert a hex string such as ‘FF0001AF’ to binary data, use the binascii.unhexlify(hex_str) function that returns the binary data represented by the hexadecimal string. Note that this converts two hex string digits to one byte, i.e., hex string ‘F0’ is converted to the byte representation 11110000, or in binary … Read more

Python Print Binary Without ‘0b’

Problem Formulation If you print a binary number, Python uses the prefix ‘0b’ to indicate that it’s a number in the binary system and not in the decimal system like normal integers. However, if you already know that the output numbers are binary, you don’t necessarily need the ‘0b’ prefix. How to print binary numbers … Read more