Some Other Applications
Binary data provides several applications like we can check if the two files are similar or not using the binary data, we can also check for a whether a file is jpeg or not (or any other image format). Let’s see the below examples for better understanding.
Example 1: Checking if the two files are same or not. Here two text files are used with the data as follows –
File 1:
File 2:
Python3
with open ( 'GFG.txt' , 'rb' ) as file1, open ( 'log.txt' , 'rb' ) as file2: data1 = file1.read() data2 = file2.read() if data1 ! = data2: print ( "Files do not match." ) else : print ( "Files match." ) |
Output:
Files do not match.
Example 2: Checking if the given image is jpeg or not.
Image used:
Python3
import binascii jpeg_signatures = [ binascii.unhexlify(b 'FFD8FFD8' ), binascii.unhexlify(b 'FFD8FFE0' ), binascii.unhexlify(b 'FFD8FFE1' ) ] with open ( 'food.jpeg' , 'rb' ) as file : first_four_bytes = file .read( 4 ) if first_four_bytes in jpeg_signatures: print ( "JPEG detected." ) else : print ( "File does not look like a JPEG." ) |
Output:
JPEG detected.
Working with Binary Data in Python
Alright, lets get this out of the way! The basics are pretty standard:
- There are 8 bits in a byte
- Bits either consist of a 0 or a 1
- A byte can be interpreted in different ways, like binary octal or hexadecimal
Note: These are not character encodings, those come later. This is just a way to look at a set of 1’s and 0’s and see it in three different ways(or number systems).
Examples:
Input : 10011011 Output : 1001 1011 ---- 9B (in hex) 1001 1011 ---- 155 (in decimal) 1001 1011 ---- 233 (in octal)
This clearly shows a string of bits can be interpreted differently in different ways. We often use the hex representation of a byte instead of the binary one because it is shorter to write, this is just a representation and not an interpretation.
Contact Us