pseudocode to python question

I’ve succesfully converted a bit of pseudo-code to the python equivalent… almost. I think I found the part that I may have gotten wrong: while ( xx + yy < (1 << 16))

what does “(1 << 16)” mean?

“<<” and “>>” are bitwise shifts in python. Might be in pseudocode, too? The expression “(1 << 16)” would be the same as “2 ** 16” (2 to the power of 16). Does this make sense?


x << y
Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y
Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.

hmm. I wonder why someone would use (1 << 16) instead of (2**16), or better yet (65536). not only would that not make sense in general, but also in this context. 65536 would not work as far as I know. perhaps it means something else.

One reason why someone would use 1 << 16 vs 2 ** 16 vs 65536 is context and clarity. When you use 1 << 16, you are telling the person reading your code “Hey, I’m doing stuff in base 2. This may or may not be for doing bit fields.” Whereas 2 ** 16 is telling the developer “Hey, I’m getting 2 to the power of 16 for something”. 65536 isn’t that useful because it doesn’t give context to what the number is.

Here’s an example:

e = 0.0625

This is extremely bad to do as a developer, because there’s nothing to say what this is for. Something like this would be more useful:

edge_length = 1.0 / 16

Now we know that the variable is to do with edge length, and we know how we got that number. Although, it isn’t 100% yet.

total_length = 1.0
steps = 16
edge_length = total_length / steps

Now we know that the edge length is calculated by getting the total length and dividing it by the number of steps. If you go back to this code in 2 years, you know exactly what’s going on. Future you will thank you.

For a processor, its simpler to shift bits right or left than making a multiplication.

That’s true, but here’s something that doesn’t make sense. I ran this code on my machine:

from timeit import timeit

def bitshift():
    1 &lt;&lt; 16
def exponent():
    2 ** 16

rounds = 1000000
print(timeit("bitshift()", setup="from __main__ import bitshift", number=rounds))
print(timeit("exponent()", setup="from __main__ import exponent", number=rounds))

And found that the exponent is a fraction faster (0.127 seconds for bitshift, and 0.087 seconds for exponent). My guess is Python is converting the bitshift to an exponent under the hood. This result will probably be far different if we compiled some C code and ran the tests.

For sure! Python is not C, and there’s still conversions taking place, classes being searched, compiling algorythms to choose… And bitwise operations make more sense in low level programming languages. :slight_smile: