Operators
Operators
Exponentiation operator always uses right side binding --> 2**2**3 = 256
Operator priorities
Reserved Words
Note: make use of the ** operator to evaluate the square root as:
and
Strings
Logical operators
AND
OR
NOT
Negation
Let’s look at the negation operators now. First the logical one:
logneg = not i
The logneg variable will be set to False – nothing more needs to be
done.
The bitwise negation goes like this:
bitneg = ~i
It may be a bit surprising: the bitneg variable value is -16. This
may seem strange, but isn’t at all. If you wish to learn more, you
should check out the binary numeral system and the rules
governing two’s complement numbers.
How do we deal with single bits?
We’ll now show you what you can use bitwise operators for.
Imagine that you’re a developer obliged to write an important piece
of an operating system. You’ve been told that you’re allowed to use
a variable assigned in the following way →
check the state of your bit – you want to find out the value of
your bit; comparing the whole variable to zero will not do
anything, because the remaining bits can have completely
unpredictable values, but you can use the following conjunction
property:
x & 1 = x
x & 0 = 0
If you apply the & operation to the FlagRegister variable
along with the following bit image:
0000000000000000000000000000001000
(note the 1 at your bit’s position) as the result, you obtain one
of the following bit strings:
0000000000000000000000000000001000if your bit was set to 1
0000000000000000000000000000000000if your bit was reset
to 0
Such a sequence of zeros and ones, whose task is to grab the
value or to change the selected bits, is called a bit
mask. Let’s build a bit mask to detect the state of your bit. It
should point to the third bit. That bit has the weight of 2 = 8.
3
reset your bit – you assign a zero to the bit while all the other
bits must remain unchanged; let’s use the same property of the
conjunction as before, but let’s use a slightly different mask –
exactly as below:
1111111111111111111111111111110111
Note that the mask was created as a result of the negation of all the
bits of TheMask variable. Resetting the bit is simple, and looks like
this (choose the one you like more) →
set your bit – you assign a 1 to your bit, while all the remaining
bits must remain unchanged; use the following disjunction
property:
x | 1 = 1
x | 0 = x
You’re now ready to set your bit with one of the following
instructions →
x ^ 1 = ~x
x ^ 0 = x
and negate your bit with the following instructions →