Bitwise and Bit Shift Operators


#1

I can not find these operators on my windows lap top ??


#2

There are not actual keys for the bit shift operators. Use two greater than or two less than

a >> 2   =>  right shift 2 places

a << 2   =>  left shift 2 places

These are not in-place operations and need to be assigned to a variable to retain the shift.


#3

Thank you , I was looking for , the | symbol , and forgot how to find my character map on my PC , but thank so much for helping me so quickly , my name is Quibow , I found it :grinning:


#4

Can anyone tell me the practical use of bitwise operations? I understand the need to teach this as a part of the Python language but how prevalent is its use in real-world application? Examples?


#5

One practical use is for flags. A single boolean can take up as much space as an integer which is significant (24 bytes). That’s 192 bits that can each serve as a boolean flag. Even if our program only has a dozen of so booleans, it can still bloat code and use a lot of memory. We can pack all those booleans into a single variable and use a mask to determine if a bit is set or unset (T or F).

Bitwise operations can also replace if conditionals, can be used to multiply by powers of two (or divide), can be used to pack bytes into an integer (compression), can be used for encryption, and can be used to swap two values without a temporary variable.

Python and Ruby (and no doubt C and Java) can swap two variables in single statement

a, b = b, a

This is done using XOR.

Let a = 77 and b = 177

>>> a = 77
>>> b = 177
>>> a = b ^ a
>>> b = a ^ b
>>> a = b ^ a
>>> a
177
>>> b
77
>>> 

If you have hardware somewhere in your sights, then bitwise operators are used extensively in the software control of said hardware. Computers use electronic bitwise operations in logic gates and other circuits such as memory.

This is all very generalized, but the practical applications can be found in many places once one begins to look. For now, just consider it a fundamental tool to have in one’s tool kit.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.