scott
scott

Reputation: 3081

What does ^ operator do?

I thought that ^ did that. I expected:

10^0=1
10^1=10
10^2=100

What I'm getting

10^0=10
10^1=11
10^2=8

the actual code is

int value = 10 ^ exp;

replacing exp for 0, 1, and 2 What does the ^ operator do?

Upvotes: 5

Views: 628

Answers (9)

Chris Flynn
Chris Flynn

Reputation: 953

As others have said, you need you use Math.pow(x, y) to do x^y in C#. The ^ operator is actually a logical XOR operator on the bits of the two numbers. More information on the logical XOR can be found here: http://msdn.microsoft.com/en-us/library/zkacc7k1.aspx

Upvotes: 1

PedroC88
PedroC88

Reputation: 3839

The thing is that ^ is equivalent for XOR, that's why 10 ^ 0 = 10 because

1010 XOR    1010 XOR
0000 =      0010 =
1010        1000

You need to use Math.Pow method.

P.S. = 10^2 actually returns 8...

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 285017

There is no operator for this. Use Math.Pow.

There is a full list of all the C# operators with linked documentation on each one.

Upvotes: 0

Kevin McKelvin
Kevin McKelvin

Reputation: 3547

^ is the XOR operator.

http://en.wikipedia.org/wiki/Xor

If you want to raise a number to a power, use

Math.Pow(num, exp);

Upvotes: 0

Paul Sonier
Paul Sonier

Reputation: 39510

In C#, the ^ operator is the logical XOR operator.

http://msdn.microsoft.com/en-us/library/6a71f45d.aspx

Upvotes: 0

Rick Liddle
Rick Liddle

Reputation: 2714

In c#, ^ is the logical XOR operator.

Upvotes: 2

Nitesh
Nitesh

Reputation: 2337

Math.Power(10,exp) works like charm...

Upvotes: 0

Yuck
Yuck

Reputation: 50855

You want to do:

Math.Pow(10, exp);

This actually produces a double though so you'll need to cast it down if you really want an int.

Upvotes: 3

Coeffect
Coeffect

Reputation: 8866

Math.Pow(x, y) to get x raised to the power of y. You were doing an XOR. C# operators

Upvotes: 11

Related Questions