PDA

Click to See Complete Forum and Search --> : Carrot sign


Arrow_Raider
Feb 20th, 2004, 04:42 PM
public class Class {

public static void main(String[] args)
{
for(int i = 1; i <= 100; i++)
{
System.out.print((i^2) + ",");
}
}
}

so i got that code, what does the carrot sign do in java, cause that sure as hell doesn't print out the squares of i...

Arrow_Raider
Feb 20th, 2004, 04:54 PM
ok, i sorta figured out what ^ does, it performs what is called bitwise exclusive or, i read some stuff on what that does and was confused...

CornedBee
Feb 21st, 2004, 08:04 AM
It manipulates the bits. You see, all numbers in computers are in binary. The number 177, for example, is in binary
10110001
The bitwise operators <<, >>, >>>, ^, &, | and ~ manipulate numbers of the bit level. ~ simply inverts all bits:
~10110001 = 01001110
<<, >> and >>> shift the bits:
10110001 << 3 = 10001000
>> and >>> shift to the right instead of left. They differ in the way new bits get inserted on the left, but I forgot which is which.
&, ^ and | perform bitwise logical operations: & is AND, ^ is XOR and | is OR.
10110001 &
01100101 =
00100001
so only where both operands have 1 has the result 1. OR means where either have 1:
10110001 |
01100101 =
11110101
and XOR where either, but not both (exclusive or):
10110001 ^
01100101 =
11010100

CornedBee
Feb 21st, 2004, 08:05 AM
Ok, for simple powers like square you usually write it in multiplications: x^2 = x*x.

For more complicated powers, you use the Math.pow function.

Dillinger4
Feb 24th, 2004, 12:33 AM
For the ~ operator you can do some simple binary manipulation to turn neg nums to positive and visa versa.

neg to pos (-n == ~n +1)

-484 = 10 0001 1100
01 1110 0011 = 483
483 + 1 = 484

pos to neg (n == ~n +1)
484 = 01 1110 0100
10 0001 1011 = - 485 + 1 = - 484

same formula applies.....

pos to neg ((n-1) ~n == (-n))
484 - 1 = 483
483 = 01 1110 0011
-484 = 10 0001 1100

CornedBee
Feb 24th, 2004, 05:40 AM
Yeah, but - does it too :)

Dillinger4
Feb 24th, 2004, 12:32 PM
Posted by CornedBee

Yeah, but - does it too :)


Yes but then all the fun would be taken out. :lol: