[Tutor] trying to understand pattern matching code

Alan Gauld alan.gauld at btinternet.com
Sat Apr 26 10:58:56 CEST 2014

On 26/04/14 09:36, rahmad akbar wrote:

> but  i still couldnt get this line though
> D = (( D << 1) + 1) & masks [ c ]

Do you understand the concept of bit shifting?
000110 shifted left gives

000110 shifted right gives

In other words the bit pattern moves left or
right and the missing bits are replaced with

The effect of shift left is to multiply the
number by two.

+ 1 just adds 1 to the resulting number

So the first bit of your line is the same as

D = ((D*2)+1)

The second part uses bitwise and with a mask chosen from a list of masks,
A bitwise and has the effect of zeroing any bit that is zero in the mask 
and keeping any bit that is one in the mask.


11100011  -> My data
00001111  -> my mask, designed to return the right hand 4 bits
00000011  -> data & mask

11100011  -> data
11110000  -> mask for leftmost 4 bits
11100000  -> data & mask

So which bits are preserved in your D after the math and masking depends 
on what the masks[c] mask looks like.

You might want to use some print statements using the bin()
function to see the actual bit patterns. (If you do you might
find that long bit patterns don;t show what you expect, if
that happens try masking the result to say 16 places
like this:

print bin(mydata & 0xFFFF)  # FFFF => 1111111111111111

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list