So what does the caret operator do?

In my previous two posts I was squaring in a tedious way. Something like this : self.size*self.size. There is nothing wrong with it, but how to cope when I would have to calculate x to the power of 12. My code would definetly become unreadable. Of course, coming from a BASIC background I first tried using the caret operator (‘^’).  But the caret operator is used in different languages for very different things.  I already knew that and just couldn’t be bothered looking it up and just used the definition of a square. But here it is: a**b gives a to the power b in Python. But if the ** operator is used to raise a number to a power, what does the caret do? It does do something because Python says:

>> 2^2
>>> 2^3
>>> 2^4

And that certainly has nothing to do with any exponent of anything..

The caret operator is a bitwise XOR operator. It only returns true (1) if exactly one of the operands is true.

(bits)  (int)

0010    2
0010    2
——    (xor)
0000    0

0010    2
0011    3
——   (xor)
0001    1

0010    2
0100    4
——    (xor)
0110    6

It actually works the same in JavaScript.



Geef een reactie

Vul je gegevens in of klik op een icoon om in te loggen. logo

Je reageert onder je account. Log uit /  Bijwerken )

Google+ photo

Je reageert onder je Google+ account. Log uit /  Bijwerken )


Je reageert onder je Twitter account. Log uit /  Bijwerken )

Facebook foto

Je reageert onder je Facebook account. Log uit /  Bijwerken )


Verbinden met %s