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
  • 705,106
  • 160
  • 1,004
  • 1,072
chicane
  • 1,831
  • 3
  • 18
  • 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
  • 359,228
  • 81
  • 502
  • 469
  • 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
  • 28,342
  • 21
  • 95
  • 123
Mitch Dempsey
  • 34,423
  • 6
  • 62
  • 72
6

It's a bitwise operator.

Example:

"hallo" ^ "hello"

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • 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
  • 51,147
  • 13
  • 111
  • 112
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
  • 28,342
  • 21
  • 95
  • 123
Cam
  • 13,963
  • 16
  • 70
  • 121
2

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

Michael Borgwardt
  • 327,225
  • 74
  • 458
  • 699
0

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

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
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