bits, bytes, bitstring, and ConstBitStream
int(x, base=10)
Convert a number or string x to an integer, or return 0 if no arguments are given.
>>> int('00100001', 2) 33 >>> int('0xff',16) 255 >>> int('ff', 16) 255
To convert to hex string:
>>> "0x%x" % (int('00100001', 2)) '0x21'
>>> chr(int('01011110',2)) '^' >>> int('01000000',2) 64 >>> chr(int('01000000',2)) '@' >>> int('01110100', 2) 116 >>> chr(int('01110100', 2)) 't' >>> ord('t') 116
The bitstring classes provides four classes:
BitStream and BitArray and their immutable versions ConstBitStream and Bits:
- Bits (object): This is the most basic class. It is immutable and so its contents can't be changed after creation.
- BitArray (Bits): This adds mutating methods to its base class.
- ConstBitStream (Bits): This adds methods and properties to allow the bits to be treated as a stream of bits, with a bit position and reading/parsing methods.
- BitStream (BitArray, ConstBitStream): This is the most versative class, having both the bitstream methods and the mutating methods.
>>> from bitstring import BitStream, BitArray >>> c = BitArray(hex='000001b3') >>> c BitArray('0x000001b3') >>> c.hex '000001b3'
>>> d = BitArray(bin='0011 00') >>> d BitArray('0b001100') >>> d.bin '001100'
>>> a = BitArray(uint=45, length=12) >>> b = BitArray(int=-1, length=7) >>> a, b (BitArray('0x02d'), BitArray('0b1111111')) >>> a.bin '000000101101' >>> b.bin '1111111'
>>> a = BitArray(bytes=b'\x00\x01\x02\xff', length=28, offset=1) >>> a BitArray('0x000205f') >>> a.bin '0000000000000010000001011111' >>> a.hex '000205f' >>> b = BitArray(bytes=open('video.mp4', 'rb').read()) >>> b BitArray('0x000000206674797069736f6d0000020069736f6d69736f32617663316d7034310000000866726565048e01fe6d64617400000000001d67640015acd941e08effc0220021c4000003000400000300ca3c58b6580000000668ebe2cb22c0000002d30605ffffcfdc45e9bde6d948b7962cd820d923eeef78323634202d20...') # length=614024968
class bitstring.ConstBitStream([auto, length, offset, **kwargs])
>>> from bitstring import ConstBitStream >>> s = ConstBitStream('0x123456') >>> s ConstBitStream('0x123456') >>> s.peek(12) # 12 bits ConstBitStream('0x123') >>> s.peek('hex:12') '123'
peek reads from the current bit position pos in the bitstring according to the fmt string or integer and returns the result. The bit position is unchanged.
read(fmt)
It reads from current bit position pos in the bitstring according the the format string and returns a single result.
int:n n bits as a signed integer. uint:n n bits as an unsigned integer. hex:n n bits as a hexadecimal string. bin:n n bits as a binary string. bits:n n bits as a new bitstring. bytes:n n bytes as bytes object.
The sample run below shows it advances 4 bits each time we read a hex number:
>>> s = ConstBitStream('0x1234') >>> s ConstBitStream('0x1234') >>> s.read('hex:4') '1' >>> s.read('hex:4') '2' >>> s.read('hex:4') '3' >>> s.read('hex:4') '4'
If we read 4 bits and output it as a binary format:
>>> s = ConstBitStream('0x1234') >>> s.read('bin:4') '0001' >>> s.read('bin:4') '0010' >>> s.read('bin:4') '0011' >>> s.read('bin:4') '0100'
Output as an unsigned integer as we read in 4 bits each time and advance:
>>> s = ConstBitStream('0x1234') >>> s.read('uint:4') 1 >>> s.read('uint:4') 2 >>> s.read('uint:4') 3 >>> s.read('uint:4') 4
pos/bitpos is a read and write property for setting and getting the current bit position in the bitstring. Can be set to any value from 0 to len.
>>> s = ConstBitStream('0x1234') >>> s.read('uint:4') 1 >>> s.pos 4 >>> s.pos += 4 >>> s.read('uint:4') 3 >>> s.read('uint:4') 4
The following code reads in video.mp4 one byte at a time, convert it to character, and then puts it into a list. It reads only the first 180 bytes.
from bitstring import ConstBitStream info = [] nbytes = 180 with open('video.mp4', 'rb)') as vfile: packet = ConstBitStream(bytes = vfile.read(nbytes), length = nbytes*8) while(packet.pos < nbytes*8): #byte = packet.read(8).hex #info.append(chr(int(byte, 16))) byte = packet.read(8).uint info.append(chr(byte)) print info
The output looks like this:
['\x00', '\x00', '\x00', ' ', 'f', 't', 'y', 'p', 'i', 's', 'o', 'm', '\x00', '\x00', '\x02', '\x00', 'i', 's', 'o', 'm', 'i', 's', 'o', '2', 'a', 'v', 'c', '1', 'm', 'p', '4', '1', '\x00', '\x00', '\x00', '\x08', 'f', 'r', 'e', 'e', '\x04', '\x8e', '\x01', '\xfe', 'm', 'd', 'a', 't', '\x00', '\x00', '\x00', '\x00', '\x00', '\x1d', 'g', 'd', '\x00', '\x15', '\xac', '\xd9', 'A', '\xe0', '\x8e', '\xff', '\xc0', '"', '\x00', '!', '\xc4', '\x00', '\x00', '\x03', '\x00', '\x04', '\x00', '\x00', '\x03', '\x00', '\xca', '<', 'X', '\xb6', 'X', '\x00', '\x00', '\x00', '\x06', 'h', '\xeb', '\xe2', '\xcb', '"', '\xc0', '\x00', '\x00', '\x02', '\xd3', '\x06', '\x05', '\xff', '\xff', '\xcf', '\xdc', 'E', '\xe9', '\xbd', '\xe6', '\xd9', 'H', '\xb7', '\x96', ',', '\xd8', ' ', '\xd9', '#', '\xee', '\xef', 'x', '2', '6', '4', ' ', '-', ' ', 'c', 'o', 'r', 'e', ' ', '1', '4', '0', ' ', 'r', '2', ' ', '1', 'c', 'a', '7', 'b', 'b', '9', ' ', '-', ' ', 'H', '.', '2', '6', '4', '/', 'M', 'P', 'E', 'G', '-', '4', ' ', 'A', 'V', 'C', ' ', 'c', 'o', 'd', 'e', 'c', ' ', '-', ' ', 'C', 'o', 'p', 'y', 'l', 'e', 'f', 't']
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization