Recent data packet parsing in Python has encountered some problems with the bitwise processing of binary data. Toss a morning, probably a little thought, write down the memo.
The problem I'm trying to solve is to determine if a certain bit of a byte is a specific value, such as determining if the first four bits of a byte are 0110.
First of all, create a document, write something in it, save it with the software can view the binary data open, I use the notepad++ in the Hex-editor plugin.
You can see that the binary data corresponding to the character ' a ' is 61 (01100001). The data for this byte is processed below.
The first is to open the file, read a byte with the read () function, encode it with 16, encode it into a str type, then convert it, the Int () function can convert a str to an int type, and the second parameter of the Int () function represents the binary. Mask is 11110000, I use mask and the byte to be processed with, you can get the contents of the first four bits of data. Here, the first four bits of 01100001 are 0110, and the end result is 01100000, or 96.
F=open (' 1.txt ', ' RB ') Data=int (F.read (1). Encode (' hex '), +) print Dataprint bin (data) Mask=0b11110000print maskres= Data&maskprint Res
bitwise processing of binary data using Python