Bitwise AND, noted as a single ampersand (
&) in most programming languages, combines two binary values into a result. Each bit in the values being combined is compared. If they’re both 0, the resulting value is 0. If either of them is 1, then the resulting value is still 0. And if they’re both 1, the result is 1. Bitwise operations can be expressed using something called a truth table.
00:55 The header row and header column contain the values of bits being compared and their intersection in the table shows the result. So, 00 in the blue meet to form 0 in the gray, 11 in the blue meet to form 1 in the gray, and the mixed values in between. Consider the following example.
01:37 Bitwise OR, noted as a single pipe symbol in most programming languages, combines two binary values. Each bit is compared, and if either of them is on, the resulting value has the corresponding bit on. 0 OR 0 is 0, 1 OR 0 is 1, 0 OR 1 is 1, and 1 OR 1 is also 1.
Up until now, all the bitwise operations you’ve seen have operated on two values. The NOT is different. It is a unary operation. Bitwise NOT is usually the tilde symbol (
~) in most programming languages and is responsible for inverting each bit in a binary number.
There are two bitwise shift operators, one for shifting left and one for shifting right. These are usually denoted as double less than (
<<) and double greater than (
>>) in most programming languages.
03:42 Each shift operation includes a parameter: a number that indicates how many positions the bits are going to shift. The following examples are a bit messy, as they combine both binary and decimal numbers.
1 shifted by two positions gives
100 binary, or decimal 4. Note that the new digits shifted into the lowest positions are all 0s.
100 shifted right by one position gives
10. The rightmost digit of the original is chopped off.
05:26 The problem is computers have limited space to store things, and that limitation has an effect on bitwise math. Consider an eight-digit binary number being stored in a place with enough space for eight digits.
05:38 What happens when you shift this left? Well, you can’t put a nine-digit number in an eight-digit space. Complications ensue. This means bitwise manipulation of binary values may not have the effect you may think it does, depending on the programming language and the data type within the language that you’re using. In theory land, everything so far has been an unsigned number—that means everything is zero or more—and all operations were logical.
06:17 Some languages even have the behavior change based on the data type being used. Did you notice the slide’s title? If you’re not familiar with the phrase, it’s Latin for buyer beware. As a purveyor of the Python programming paradigm, you may find everything isn’t peachy.
Become a Member to join the conversation.