Discussion:
[C] ^ operator?
(too old to reply)
John Smith
2003-11-21 18:20:37 UTC
Permalink
What does the ^ (circumflex) operator do in C?

The code:

int a = 100, b = 10;
int c = a ^ b;
printf("c == %d\n", c);

produces the output: c == 110

What's going on here besides addition?
Gene Wirchenko
2003-11-21 18:32:35 UTC
Permalink
Post by John Smith
What does the ^ (circumflex) operator do in C?
int a = 100, b = 10;
int c = a ^ b;
printf("c == %d\n", c);
produces the output: c == 110
What's going on here besides addition?
It is doing a bitwise exclusive or (also known as a half-add).

Sincerely,

Gene Wirchenko
Mike Wahler
2003-11-21 18:38:04 UTC
Permalink
Post by John Smith
What does the ^ (circumflex) operator do in C?
int a = 100, b = 10;
int c = a ^ b;
printf("c == %d\n", c);
produces the output: c == 110
What's going on here besides addition?
<quote>

ISO/IEC 9899:1999 (E)

[....]

6.5.11 Bitwise exclusive OR operator

Syntax

1 exclusive-OR-expression:
AND-expression
exclusive-OR-expression ^ AND-expression

Constraints

2 Each of the operands shall have integer type.

Semantics

3 The usual arithmetic conversions are performed on the operands.

4 The result of the ^ operator is the bitwise exclusive OR
of the operands (that is, each bit in the result is set
if and only if exactly one of the corresponding bits in
the converted operands is set).

</quote>

-Mike
Thomas Matthews
2003-11-21 18:39:11 UTC
Permalink
Post by John Smith
What does the ^ (circumflex) operator do in C?
int a = 100, b = 10;
int c = a ^ b;
printf("c == %d\n", c);
produces the output: c == 110
What's going on here besides addition?
The ^ (circumflex) operator in C is bit-wise exclusive
OR (a.k.a. XOR). Here is the truth table:
A B A XOR B
---------------
0 0 0
0 1 1
1 0 1
1 1 0

So in your example, converting to binary:
A: 0 1 1 0 0 1 0 0 (64 hex, 100 decimal)
B: 0 0 0 0 1 0 1 0 (0A hex, 10 decimal)
--------------------
0 1 1 0 1 1 1 0 (6E hex, 110 decimal)

This is NOT addition.

You may want to search the web for "Boolean Arithmetic".
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book
Continue reading on narkive:
Loading...