# [Tutor] trying to understand pattern matching code

Sat Apr 26 18:08:38 CEST 2014

```hi Alan,

your explanation clears most things, super thanks!!

On Sat, Apr 26, 2014 at 10:58 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> 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?
> ie
> 000110 shifted left gives
> 001100
>
> and
> 000110 shifted right gives
> 000011
>
> In other words the bit pattern moves left or
> right and the missing bits are replaced with
> zeros.
>
> 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.
>
> So
>
> 11100011  -> My data
> 00001111  -> my mask, designed to return the right hand 4 bits
> 00000011  -> data & mask
>
> Similarly
> 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
>
> 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
>
> HTH
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor

--
many thanks
mat
```