8

I came across this line of code in an application I am revising:

substr($sometext1 ^ $sometext2, 0, 512);

What does the ^ mean?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
chicane
  • 1,991
  • 3
  • 19
  • 15

7 Answers7

8

^ is the bitwise exclusive OR operator. For each bit in a value, it looks to see if that bit is the same in the other value; if it is the same, a 0 is output in its place, otherwise a 1 is output. For example:

  00001111
^ 01010101
  --------
  01011010
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • How does that work on strings? (re [Michael Borgwardt's answer](http://stackoverflow.com/questions/2724936/what-does-mean-in-php/2724974#2724974)) – Peter Mortensen Dec 28 '15 at 15:41
7

XOR (exclusive OR):

$a ^ $b means bits that are set in $a or $b, but not both, are set.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mitch Dempsey
  • 38,725
  • 6
  • 68
  • 74
6

It's a bitwise operator.

Example:

"hallo" ^ "hello"

It outputs the ASCII values #0 #4 #0 #0 #0 ('a' ^ 'e' = #4).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • im having tough time understanding about the ascii values, if we take a and e as binary equivalents like so: a=01100101 e=01100001 --------- xor=00000100 is this right? – chicane Apr 28 '10 at 01:20
2

It's the XOR (exclusive-or) operator. For strings it's used as simple encryption.

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
2

In PHP, ^ means 'bitwise XOR'. Your code XORs together two strings, then returns at most the first 512 characters.

In other words it does this:

return (at most the first 512 characters of (someText1 XOR someText2))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cam
  • 14,930
  • 16
  • 77
  • 128
2

That's the bitwise OR operator - in PHP, it also applies to strings.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
0

^ matches the starting position within the string. In line-based tools, it matches the starting position of any line.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
huh
  • 1
  • that would be a regular expression – Nils Apr 27 '10 at 20:55
  • which it would do since the first character that does not match is now XOR'd and will show up as a 1. I guess it would depend on what the original code was trying to accomplish - based on this example of "what does this do" .. we would of course need to know more information - as opposed to "what does this "^" character do. – huh Apr 27 '10 at 21:03