The ^ operator

T

Tuvas

What exactly does the ^ operator do? I've seen, for example, that
3^4=7, 3^5=8. but 3^3=0. Is it just adding them together if they are
not equal, and if they are equal, outputs 0, or what? Thanks!
 
P

Peter Hansen

Tuvas said:
What exactly does the ^ operator do? I've seen, for example, that
3^4=7, 3^5=8. but 3^3=0. Is it just adding them together if they are
not equal, and if they are equal, outputs 0, or what? Thanks!

It performs an "exclusive-OR" (XOR) operation on the binary data
corresponding to those values. Where the boolean AND operation returns
a 1 where both inputs are 1 and a 0 otherwise, and boolean OR returns a
1 if either input is 1 but 0 otherwise, the XOR operator returns a 1 if
the two inputs are different (i.e. one is 0 and the other is 1) but a 0
if they are the same.

When done on the binary value, each corresponding bit is compared using
the above logic. For example, 3 is 0011 in binary, and 4 is 0100, so:

011 binary for 3
^ 100 binary for 4
---
= 111 (which is binary for 7).

(match up the binary digits vertically, so the first digit in the result
comes from the 0 and the 1 above it, in the two input values).

-Peter
 
S

Steve Holden

Tuvas said:
What exactly does the ^ operator do? I've seen, for example, that
3^4=7, 3^5=8. but 3^3=0. Is it just adding them together if they are
not equal, and if they are equal, outputs 0, or what? Thanks!

^ is the "bit XOR" operation. It treats its left and right operands as
binary numbers: the result has a one-bit in those bit positions where
one operand has a zero and the other has a one.

A B | A XOR B
----+--------
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 0

If you want exponentiation, try **.

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,264
Messages
2,571,323
Members
48,006
Latest member
TerranceCo

Latest Threads

Top