I just started reading the book recently and became curious as to whether other readers had commented on the section about bitwise operators, because it was indeed a bit of a challenge. Like saltycraig I'm just (barely) past beginner's level. (I got an introduction to some Java programming many years ago). Now I am in a situation where I have very specific and relatively simple programming needs for a business, and felt it would be nice to use that need to learn some more programming. I purchased this book for three reasons: I immediately identified with "WHO THIS BOOK IS FOR" in the introduction, I liked the structure, and, most importantly, I was looking for a book with practical exercises (including solutions!).
Fortunately I started reading during a holiday and had plenty of time to google around to learn more about bitwise operators. In particular, the following example in step 4 on page 37 was difficult to understand (despite the How-it-works comments on the next page):
Code:
>>> bin(bits.NOT(0b0101))
'-0b110'
But I agree that after I had figured out the details, it was a nice example that immediately gives the reader some pretty fundamental insights into programming basics.
However, as a reader I would have appreciated very much if there had been a short explanation, only a few sentences, to explain 1) how byte size is related to the bit representation of numbers, 2) the concept of two's complement for representing negative numbers, and 3) that there is a difference between the computer's physical bit representation of the number and Python's binary representation of that number. Once this is figured out, it's easy to see why 0b0101 in the example is represented (in 8 bits for simplicity) as 00000101. Performing bitwise NOT (switching the ones and zeros) on this trivially gives 11111010, which is (
by definition) the two's complement representation of the number -6. And in Python the binary representation of 6 is '0b110', so -6 is simply '-0b110'.
Code:
>>> 0b110
6
>>> -0b110
-6
In the next step of the example it is necessary to understand the conversion between binary and hexadecimal numbers, which is pretty straightforward, but some readers might appreciated a little nudge in the right direction. Likewise, the concept of a bitmask deserves an extra sentence to explain it to the newcomers.
I learned a lot from studying this example, but I spent several hours over the course of a couple of days before it made sense.