Python also has a full set of bitwise operators for operating on binary values, and occasionally this comes in handy. It's a little bit difficult to show, because when you print a value, for example if I just say 5 here, it will print it in decimal. Even if I specify it in binary, if I say it 0b0101, which is a five, it still prints it in decimal. So I am going to write a little one-line function, and I'll call it b for printing binary values.
I am going to use a format string here, and we'll learn more about those in a later chapter. The format method of the string, like that, and now when I say b5 like that, it prints the binary value to 8 places. That's basically what that format string does inside the curly braces, the :08b, that prints out a binary value to 8 places.
So now we can look at the binary operators, and we can see what they do on a bitwise level. So, we are going to define a couple of values, and we will call them x and y. And x, we'll give it a couple of fives, so that it's 010101 et cetera. We will do that like this. And y, we'll do the same thing, but with the opposite bits and that happens to be xaa in hexadecimal.
So if we look at these values, x looks like that and y looks like that. So the or of these two values should be x|y, and the vertical bar there is the or operator. We will have all the bits set, like that, and the and of the two values, which is with the ampersand, will have all the bits cleared. The exclusive or will look just like the or.
So instead, let's take the exclusive or of, say, x and, say, 0 and that will look like that. Or if we take the exclusive or of x and all the bits on, it will look like that, because all of the bits get flipped. We also have shift operators. We can say x shifted left by four bits, and there we have four clear bits on the right, or we can say x shifted to the right by four bits, and it clears all the bits to the left.
We have the one's compliment operator which is the unary operator and it just looks like that, a little tilde. Since it operates on the word size of the implementation, which is more than the 8 bits that I am printing, it gets a sign extension, and it ends up looking like that. So those are the bitwise or binary operators. The word binary could mean having to do with two values. So we call them bitwise operators. Those are the bitwise operators available in Python.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 98588 Viewers
61 Video lessons · 85887 Viewers
71 Video lessons · 69766 Viewers
56 Video lessons · 102075 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
Your file was successfully uploaded.