This question already has answers here:
What does the caret (^) operator do?
(5 answers)
Closed 7 months ago.
In the book "Fluent Python" the example 10.11 goes like this:
n = 0
for i in range(1, 6):
n ^= i
1 is the value of n at the end of the loop.
I'd really like to know how this ^= operator works.
This is the bitwise XOR operator.
per your example, let each row represent iteration i in the for loop.
0^1 xor: 1
1^2 xor: 3
3^3 xor: 0
0^4 xor: 4
4^5 xor: 1
Let us look at row 2, where i=2.
Assume we are using binary rather than base 10.
1^2 is equivalent to the following
0001 = 1 (base 10)
XOR
0010 = 2 (base 10)
Returns
0011 = xor result = 3 (base 10)
Related
This question already has answers here:
>> operator in Python
(5 answers)
Closed 6 years ago.
Someone sent me this equation but I don't understand what it means.
result = ((~c1) >> 1) & 0x0FFFFFF
It has to do with converting the binary from a wiegand reader.
Reference
The >> operator in Python is a bitwise right-shift. If your number is 5, then its binary representation is 101. When right-shifted by 1, this becomes 10, or 2. It's basically dividing by 2 and rounding down if the result isn't exact.
Your example is bitwise-complementing c1, then right-shifting the result by 1 bit, then masking off all but the 24 low-order bits.
This statement means:
result = # Assign a variable
((~c1) # Invert all the bits of c1
>> 1) # Shift all the bits of ~c1 to the right
& 0x0FFFFFF; # Usually a mask, perform an & operator
The ~ operator does a two's complement.
Example:
m = 0b111
x = 0b11001
~x == 0b11010 # Performs Two's Complement
x >> 1#0b1100
m == 0b00111
x == 0b11001 # Here is the "and" operator. Only 1 and 1 will pass through
x & m #0b 1
This question already has answers here:
How to do a bitwise NOR Gate in Python (editing python maths to work for me)
(2 answers)
Closed 9 years ago.
I'm trying to understand the code from an answer I received yesterday:
2nd: How to make a bitwise NOR gate
1st: How to do a bitwise NOR Gate in Python (editing python maths to work for me)
a=0b01100001
b=0b01100010
bin((a ^ 0b11111111) & (b ^ 0b11111111))
I now understand EVERYTHING except:
the & between the two values
and the ^ 11111111 ( I know that 0b is base 2)
Can someone please explain these?
How NOR works?
The expression x NOR y can be broken using AND, OR, and NOT:
x NOR y == NOT(x OR y) == NOT(x) AND NOT(y)
So, for your given values:
a=0b01100001
b=0b01100010
a NOR b would be NOT(a) AND NOT(b). Now think how would you do a NOT(a)? You just need to flip the bits. What is the way to flip the bits? An XOR(^). How?
0 ^ 1 == 1
1 ^ 1 == 0
So, taking the XOR of any bit with 1 will flip that bit. i.e. NOT(somebit) == a XOR somebit. So, in your case, just take an XOR of each bits in a and b with 1 will get you the NOT:
01100001
^ 11111111
------------
10011110
That is, we do an XOR with 11111111. Note the number of 1's is same as the number of bits in a.
Putting it together:
NOT(a) = a ^ 0b11111111
NOT(b) = b ^ 0b11111111
Now, that we got the NOTs of a and b, let's do an AND. So, what's the way to do an AND? Just do a bitwise &.
That's pretty simple:
NOT(a) AND NOT(b) == (a ^ 0b11111111) & (b ^ 0b11111111)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the reason for having ‘//’ in Python?
While trying to do an exercise on summing digits, I stumbled on this solution:
def sum_digits(n):
import math
total = 0
for i in range(int(math.log10(n)) + 1):
total += n % 10
n //= 10
return total
My question is, what does the second to last line do? How is that proper syntax?
That implements what is called floor division. Floor division (indicated by // here) truncates the decimal and returns the integer result, while 'normal' division returns the answer you may 'expect' (with decimals). In Python 3.x, a greater distinction was made between the two, meaning that the two operators return different results. Here is an example using Python 3:
>>> 10 / 3
3.3333333333333335
>>> 10 // 3
3
Prior to Python 3.x, there is no difference between the two, unless you use the special built-in from __future__ import division, which then makes the division operators perform as they would in Python 3.x (this is using Python 2.6.5):
In [1]: 10 / 3
Out[1]: 3
In [2]: 10 // 3
Out[2]: 3
In [3]: from __future__ import division
In [4]: 10 / 3
Out[4]: 3.3333333333333335
In [5]: 10 // 3
Out[5]: 3
Therefore when you see something like n //= 10, it is using the same +=/-=/*=/etc syntax that you may have seen, where it takes the current value of n and performs the operation before the equal sign with the following variable as the second argument, returning the result into n. For example:
In [6]: n = 50
In [7]: n += 10
In [8]: n
Out[8]: 60
In [9]: n -= 20
In [10]: n
Out[10]: 40
In [11]: n //= 10
In [12]: n
Out[12]: 4
// is the floor division operator. It always truncates the return value to the largest integer smaller than or equal to the answer.
The second to last line is a combination of operators, in a way, including an uncommon one, which is why it's a little confusing.
Let's piece it apart.
First, // in Python is floor division, which basically is division rounded down to the nearest whole number. Thus,
>>> 16//5
3
>>> 2//1
2
>>> 4//3
1
>>> 2//5
0
Finally, the = is there because of a Python syntax that allows one to perform an operation on a variable, and then immediately reassign the result to the variable. You've probably seen it most commonly in +=, as:
>>> a = 5
>>> a += 7
>>> a
12
In this case, //= means "perform floor division, floor dividing the variable by the second argument, then assign the result to the original input variable." Thus:
>>> a = 10
>>> a //= 6
>>> a
1
for the assignment in Python A += B equals to A = A + B ,A *= B equals to A = A * B
same thing applies to "Floor Divide" as well , A //= B equals to A = A // B
Floor Division means return the truncated integer number
>>> 5 // 3 # 1.6
1 # 0.6 will be throw off
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python - '>>' operator
There's some code that does this:
x = n - 1 >> 1
I don't know if I have to provide more syntax, but what does the >> mean? I've been searching all over, but can't find any explanation.
Its a shift right logical, it is a bitwise operation that tells the number to shift in bits by that amount. In this case you are shifting by 1, which is equivalent to dividing by 2.
If you do not understand bitwise operations, a simple conversion for you to remember would be this.
x >> n
is equivalent to
x // (2**n)
It is the bitwise shift-to-right operator.
It shifts the bits of the integer argument to the right by the number on the right-hand side of the expression:
>>> 8 >> 2
2
or illustrated in binary:
>>> bin(0b1000 >> 2)
'0b10'
Your code example is actually doubly confusing as it mixes arithmetic and bitwise operations. It should use the '//' integer division operation instead:
x = (n - 1) // 2
x >> y
is equivalent to
x.__rshift__(y)
which, as others have said, is meant to be a bitshift.
>> is the bitwise right shift operator. This operator move all bits in the first operand right by the second operand.
So: a >> b = a // 2**b
Example:
36 in binary is 0b100100
36 >> 1 is 0b10010 (last binary digit or "bit" is removed) which is 18
36 >> 2 is 0b1001 (2 bits removed) which is 9
Note that the operator goes after addition. So the code does n-1 first, then right shift it by 1 bit (i.e. divides by 2).
This question already has answers here:
Bitwise operation and usage
(17 answers)
Closed 10 months ago.
I came across the following code
numdigits = len(cardNumber)
oddeven = numdigits & 1
what exactly is going on here? I'm not sure what the "&" is doing.
Answer
The & symbol is a bitwise AND operator. Used with 1, it basically masks the value to extract the lowest bit, or in other words will tell you if the value is even or odd.
More Info on Python's & operator
For more information, see: http://wiki.python.org/moin/BitwiseOperators
Why it Works to check Odd vs. Even
EDIT: Adding this section since this answer is getting some love
The reason why ANDing a value with 1 tells if the value is odd or even may not be obvious at first.
The binary representation of a number is essentially the sum of a series of YES or NO for each power of 2 moving leftward starting in the rightmost digit with 1, 2, 4, 8, ...
There is only one way to represent any number in this way. E.g. the number 13 (base 10) can be written in binary as "1101" (or hexadecimal as 0xD, but that's beside the point). See here:
1 1 0 1
x x x x
8 4 2 1
= = = =
8 + 4 + 0 + 1 = 13
Notice that aside from the rightmost binary digit, all other 1 digits will add an even number (i.e. a multiple of 2) to the sum. So the only way to get an odd final sum is to add that odd 1 from the rightmost digit. So if we're curious if a number is odd or even, we can look at its binary representation and ignore everything except for the rightmost digit.
To do this, we use the bitwise AND operator. The value 1 in binary is expressed as 1:
0 0 0 1
x x x x
8 4 2 1
= = = =
0 + 0 + 0 + 1 = 1
ANDing a value with 1 like this will result in 1 if the value's rightmost bit is set, and 0 if it is not.
And because 0 is generally considered "false" in most languages, and non-zero values considered "true", we can simply say as a shortcut:
if (value & 1): do_something_with_odd_value()...
& is also used for taking the intersection of two Python sets:
set1 = {0,1,2,3}
set2 = {2,3,4,5}
print(set1 & set2)
>>>set([2, 3])
More generally, Python allows operator overloading, meaning you can write classes that re-interpret what the & operator does. This is how libraries such as Pandas and Numpy hijack &.
It's a bitwise operation, in this case assigning zero to oddeven if cardNumber has an even number of elements (and one otherwise).
As an example: suppose len(cardNumber) == 235. Then numdigits == 235, which is 0b11101011 in binary. Now 1 is '0b00000001' in binary, and when you "AND" them, bitwise, you'll get:
11101011
&
00000001
----------
= 00000001
Similarly, if numdigits were 234, you would get:
11101010
&
00000001
----------
= 00000000
So, it's basically a obfuscated way of checking if len(cardNumber) % 2. Probably written by someone with a C background, because it is not very pythonic - readability counts!
& is a bitwise and, which is an efficient way to do bit-level calculations. It is taking numdigits and and-ing it with 1, bit-by-bit.
It's a binary bitwise AND operator.