BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

bits, bytes, bitstring, and ConstBitStream

python_logo




Bookmark and Share





bogotobogo.com site search:

bit manipulations
int
 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

hex string

To convert to hex string:

>>> "0x%x" % (int('00100001', 2))
'0x21'


char
>>> chr(int('01011110',2))
'^'
>>> int('01000000',2)
64
>>> chr(int('01000000',2))
'@'

>>> int('01110100', 2)
116
>>> chr(int('01110100', 2))
't'
>>> ord('t')
116


bitstring

bitstring classes

The bitstring classes provides four classes:

BitStream and BitArray and their immutable versions ConstBitStream and Bits:

  1. Bits (object): This is the most basic class. It is immutable and so its contents can't be changed after creation.
  2. BitArray (Bits): This adds mutating methods to its base class.
  3. 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.
  4. BitStream (BitArray, ConstBitStream): This is the most versative class, having both the bitstream methods and the mutating methods.


hexstring
>>> from bitstring import BitStream, BitArray
>>> c = BitArray(hex='000001b3')
>>> c
BitArray('0x000001b3')
>>> c.hex
'000001b3'


binary string
>>> d = BitArray(bin='0011 00')
>>> d
BitArray('0b001100')
>>> d.bin
'001100'


from int
>>> a = BitArray(uint=45, length=12)
>>> b = BitArray(int=-1, length=7)
>>> a, b
(BitArray('0x02d'), BitArray('0b1111111'))
>>> a.bin
'000000101101'
>>> b.bin
'1111111'


from raw byte
>>> 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




ConstBitStream class
 class bitstring.ConstBitStream([auto, length, offset, **kwargs])


peek
>>> 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
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 and bitpos

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']




more



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

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







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 ...

Selenium WebDriver

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 ...


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm




Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master