strange behaviour of ^ (basic question)

P

pauldepstein

I have lines in my code like:

const int depth = 4;

int node_total = (depth + 1)^2;

This is giving a very different value for node_total than the seemingly
equivalent

int node_total = (depth + 1) * (depth + 1);

Why? What is the difference?

For example depth = 4; seems to lead to node_total == 7;

in my earlier version: int node_total = (depth + 1) ^2;

In other words, my first guess is that ^ is behaving like + (although I
would need more values to check this.)

Can anyone explain what ^ is doing?

As an incidental point, it is hard to google-search such inquiries --
the google search engine doesn't treat technical notation like ^ or ++
well at all, and is unable to judge what is "similar" to the
search-engine text.

I wonder if the google people are working on that (or if there is a
user's trick I'm missing.)

Paul Epstein
 
S

Stuart Golodetz

^ is bitwise-xor, x ^ 2 means x XOR 2, not x squared

4 + 1 = 5 (decimal) = 101 (binary)
2 (decimal) = 010 (binary)

101 xor 010 = 111 (binary) = 4 + 2 + 1 = 7 (decimal)

HTH,
Stu
 

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
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top