본문 바로가기

스터디 로그/Computer Science

[Python] Bit operator

x << y

returns x with the bits shifted to the left by y places (and new bits on the right-side are zeros)

same as multiplying x by 2^y

1 << 1 --> 0b10 (2 in decimal, same as 1 *2 = 2)

1 << 2 --> 0b100 (4 in decimal, same as 1 * 2^2 = 4)

 

 

x >> y

returns x with the bits shifted to the right by y places (and new bits on the left-side are zeros)

same as dividing x by 2^y

1 >> 1 --> 0b01 >> 1 --> 0b00 (0 in decimal, same as 1 // 2^1 = 1 // 2 = 0)

2 >> 1 --> 0b10 >> 1 --> 0b01 (1 in decimal, same as 2 // 2^1 = 1)

3 >> 1 --> 0b11 >> 1 --> 0b01 (1 in decimal, same as 3 // 2^1 = 1)

4 >> 1 --> 0b100 >> 1 --> 0b10 (2 in decimal, same as 4 // 2^2 = 2)

 

in an example of converting latitude/longitude degrees to tiles + tiles to latitude/longitude degrees

n = 1 << zoom: effectively multiplying 1 by 2^zoom

 


References

https://stackoverflow.com/questions/22832615/what-do-and-mean-in-python

 

What do >> and << mean in Python?

I notice that I can do things like 2 << 5 to get 64 and 1000 >> 2 to get 250. Also I can use >> in print: print >>obj, "Hello world" What is happening here?

stackoverflow.com