0

In a web page, I see following script snippet.

(d.charCodeAt(i)^k.charCodeAt(i)).toString()

It was a part from a for-loop, and I know what charCodeAt(i) is, but I really wondered what is the functionality of ^ sign... I make some search but failed to find anything...

What is ^ and what function or operator exists in Python or other programming languages that do the same job?

kaya3
  • 47,440
  • 4
  • 68
  • 97
Mp0int
  • 18,172
  • 15
  • 83
  • 114

3 Answers3

4

It is the bitwise XOR operator. From the MDN docs:

[Bitwise XOR] returns a one in each bit position for which the corresponding bits of either but not both operands are ones.

Where the operands are whatever is on the left or right of the operator.

For example, if we have two bytes:

A 11001100
B 10101010

We end up with

Q 01100110

If a bit in A is set OR a bit in B is set, but NOT both, then the result is a 1, otherwise it is 0.


In the example you give, it will take the binary representation of the ASCII character code from d.charCodeAt(i) and k.charCodeAt(i) and XOR them. It does the same in Python, C++ and most other languages. It is not to be confused with the exponential operator in maths-related contexts; languages will provide a pow() function or similar. JavaScript for one has Math.pow(base, exponent).

Bojangles
  • 99,427
  • 50
  • 170
  • 208
3

In Javascript it's the bitwise XOR operator - exclusive or. Only returns true if one or the other of the operands are true, but if they're both true or both false, it returns false.

In Python, it does the same thing.

Wikipedia's XOR page.

Joe
  • 15,669
  • 4
  • 48
  • 83
2

It's a bitwise XOR. It performs an "exclusive or" in each bit of the operands.

mgibsonbr
  • 21,755
  • 7
  • 70
  • 112