## How to Decode a Hex String in Python?

π¬ Question: How to Decode a Hex String in Python? Decode Hex String To decode a hexadecimal Python string, use these two steps: Here’s how you can chain the two methods in a single line of Python code: Here’s why you use the first part of the expression—to obtain a bytes object first: β­ Recommended … Read more

## 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 Convert Bytes to CSV

If you get a binary input of tabular structured data, you can convert it to CSV easily by using str(byte)[2:-1] slicing to get rid of the b’…’ byte wrapper and apply string.replace(‘\t’, ‘,’) on the result to replace tabular characters with commas. Problem Formulation For example, say you have the following bytes format in your … 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