bitwise processing of binary data using Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.