Python strtok equvialent

Thursday, June 2, 2011

C programmers usually use strtok to perform operation on string with standing patterns. In Python, we can use re.split to get similar result.

Example:

>>> import re
>>> st = "9394 811 813 815"
>>> result = [str(x) for x in filter(None, re.split('[ ,\n,\t]',st))]
>>> print result
['9394', '811', '813', '815']
>>>

Python read binary file

Wednesday, June 1, 2011

To read binary file,
fp = open(ifile,"rb")

To read 1 byte from fp,
byte = fp.read(1)

To read 30 bytes from fp,
block = fp.read(30)
block = fp.read(30)

To read the bytes from a block of binary data,
(Year,) = struct.unpack('b',block[3:4])
(Month,) = struct.unpack('b',block[4:5])
(Day,) = struct.unpack('b',block[5:6])
(Hour,) = struct.unpack('b',block[6:7])
(Minute,) = struct.unpack('b',block[7:8])
(Second,) = struct.unpack('b',block[8:9])
recdate = str(Year) + '-' + str(Month) + '-' + str(Day) + ' ' + str(Hour) + ':' + str(Minute)

You should include "import struct" so that you can use the struct module.

To read text from binary data:
(Cellname,) = struct.unpack('8s',blk[2:10])

The format characters are repeated here for quick reference.
Format C Type Python type Standard size Notes
x pad byte no value
c char string of length 1 1
b signed char integer 1 (3)
B unsigned char integer 1 (3)
? _Bool bool 1 (1)
h short integer 2 (3)
H unsigned short integer 2 (3)
i int integer 4 (3)
I unsigned int integer 4 (3)
l long integer 4 (3)
L unsigned long integer 4 (3)
q long long integer 8 (2), (3)
Q unsigned long
long
integer 8 (2), (3)
f float float 4 (4)
d double float 8 (4)
s char[] string
p char[] string
P void * integer (5), (3)

More info of using struct can be found here:
http://docs.python.org/library/struct.html

Python Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.
Assume if a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100

a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
There are following Bitwise operators supported by Python language
OperatorDescriptionExample
&Binary AND Operator copies a bit to the result if it exists in both operands. (a & b) will give 12 which is 0000 1100
|Binary OR Operator copies a bit if it exists in eather operand. (a | b) will give 61 which is 0011 1101
^Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49 which is 0011 0001
~Binary Ones Complement Operator is unary and has the efect of 'flipping' bits. (~a ) will give -60 which is 1100 0011
<<Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. a << 2 will give 240 which is 1111 0000
>>Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. a >> 2 will give 15 which is 0000 1111