What function does the ^ (caret) operator serve in Java?
When I try this:
int a = 5^n;
...it gives me:
for n = 5, returns 0
for n = 4, returns 1
for n = 6, returns 3
...so I guess it doesn't perform exponentiation. But what is it then?
The ^ operator in Java
^ in Java is the exclusive-or ("xor") operator.
Let's take 5^6 as example:
(decimal) (binary)
5 = 101
6 = 110
------------------ xor
3 = 011
This the truth table for bitwise (JLS 15.22.1) and logical (JLS 15.22.2) xor:
^ | 0 1 ^ | F T
--+----- --+-----
0 | 0 1 F | F T
1 | 1 0 T | T F
More simply, you can also think of xor as "this or that, but not both!".
See also
Wikipedia: exclusive-or
Exponentiation in Java
As for integer exponentiation, unfortunately Java does not have such an operator. You can use double Math.pow(double, double) (casting the result to int if necessary).
You can also use the traditional bit-shifting trick to compute some powers of two. That is, (1L << k) is two to the k-th power for k=0..63.
See also
Wikipedia: Arithmetic shift
Merge note: this answer was merged from another question where the intention was to use exponentiation to convert a string "8675309" to int without using Integer.parseInt as a programming exercise (^ denotes exponentiation from now on). The OP's intention was to compute 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0 = 8675309; the next part of this answer addresses that exponentiation is not necessary for this task.
Horner's scheme
Addressing your specific need, you actually don't need to compute various powers of 10. You can use what is called the Horner's scheme, which is not only simple but also efficient.
Since you're doing this as a personal exercise, I won't give the Java code, but here's the main idea:
8675309 = 8*10^6 + 6*10^5 + 7*10^4 + 5*10^3 + 3*10^2 + 0*10^1 + 9*10^0
= (((((8*10 + 6)*10 + 7)*10 + 5)*10 + 3)*10 + 0)*10 + 9
It may look complicated at first, but it really isn't. You basically read the digits left to right, and you multiply your result so far by 10 before adding the next digit.
In table form:
step result digit result*10+digit
1 init=0 8 8
2 8 6 86
3 86 7 867
4 867 5 8675
5 8675 3 86753
6 86753 0 867530
7 867530 9 8675309=final
As many people have already pointed out, it's the XOR operator. Many people have also already pointed out that if you want exponentiation then you need to use Math.pow.
But I think it's also useful to note that ^ is just one of a family of operators that are collectively known as bitwise operators:
Operator Name Example Result Description
a & b and 3 & 5 1 1 if both bits are 1.
a | b or 3 | 5 7 1 if either bit is 1.
a ^ b xor 3 ^ 5 6 1 if both bits are different.
~a not ~3 -4 Inverts the bits.
n << p left shift 3 << 2 12 Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions.
n >> p right shift 5 >> 2 1 Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions.
n >>> p right shift -4 >>> 28 15 Shifts the bits of n right p positions. Zeros are shifted into the high-order positions.
From here.
These operators can come in handy when you need to read and write to integers where the individual bits should be interpreted as flags, or when a specific range of bits in an integer have a special meaning and you want to extract only those. You can do a lot of every day programming without ever needing to use these operators, but if you ever have to work with data at the bit level, a good knowledge of these operators is invaluable.
It's bitwise XOR, Java does not have an exponentiation operator, you would have to use Math.pow() instead.
XOR operator rule =>
0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
Binary representation of 4, 5 and 6 :
4 = 1 0 0
5 = 1 0 1
6 = 1 1 0
now, perform XOR operation on 5 and 4:
5 ^ 4 => 1 0 1 (5)
1 0 0 (4)
----------
0 0 1 => 1
Similarly,
5 ^ 5 => 1 0 1 (5)
1 0 1 (5)
------------
0 0 0 => (0)
5 ^ 6 => 1 0 1 (5)
1 1 0 (6)
-----------
0 1 1 => 3
It is the XOR bitwise operator.
Lot many people have already explained about what it is and how it can be used but apart from the obvious you can use this operator to do a lot of programming tricks like
XORing of all the elements in a boolean array would tell you if the array has odd number of true elements
If you have an array with all numbers repeating even number of times except one which repeats odd number of times you can find that by XORing all elements.
Swapping values without using temporary variable
Finding missing number in the range 1 to n
Basic validation of data sent over the network.
Lot many such tricks can be done using bit wise operators, interesting topic to explore.
XOR operator rule
0 ^ 0 = 0
1 ^ 1 = 0
0 ^ 1 = 1
1 ^ 0 = 1
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
a^b ==> 0011 1100 (a)
0000 1101 (b)
------------- XOR
0011 0001 => 49
(a ^ b) will give 49 which is 0011 0001
As others have said, it's bitwise XOR. If you want to raise a number to a given power, use Math.pow(a , b), where a is a number and b is the power.
AraK's link points to the definition of exclusive-or, which explains how this function works for two boolean values.
The missing piece of information is how this applies to two integers (or integer-type values). Bitwise exclusive-or is applied to pairs of corresponding binary digits in two numbers, and the results are re-assembled into an integer result.
To use your example:
The binary representation of 5 is 0101.
The binary representation of 4 is 0100.
A simple way to define bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.
With 4 and 5, the only difference is in the last place; so
0101 ^ 0100 = 0001 (5 ^ 4 = 1) .
It is the Bitwise xor operator in java which results 1 for different value of bit (ie 1 ^ 0 = 1) and 0 for same value of bit (ie 0 ^ 0 = 0) when a number is written in binary form.
ex :-
To use your example:
The binary representation of 5 is 0101.
The binary representation of 4 is 0100.
A simple way to define Bitwise XOR is to say the result has a 1 in every place where the two input numbers differ.
0101 ^ 0100 = 0001 (5 ^ 4 = 1) .
To perform exponentiation, you can use Math.pow instead:
https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Math.html#pow%28double,%20double%29
As already stated by the other answer(s), it's the "exclusive or" (XOR) operator. For more information on bit-operators in Java, see: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/op3.html
That is because you are using the xor operator.
In java, or just about any other language, ^ is bitwise xor,
so of course,
10 ^ 1 = 11.
more info about bitwise operators
It's interesting how Java and C# don't have a power operator.
It is the bitwise xor operator in java which results 1 for different value (ie 1 ^ 0 = 1) and 0 for same value (ie 0 ^ 0 = 0).
^ is binary (as in base-2) xor, not exponentiation (which is not available as a Java operator). For exponentiation, see java.lang.Math.pow().
It is XOR operator. It is use to do bit operations on numbers. It has the behavior such that when you do a xor operation on same bits say 0 XOR 0 / 1 XOR 1 the result is 0. But if any of the bits is different then result is 1.
So when you did 5^3 then you can look at these numbers 5, 6 in their binary forms and thus the expression becomes (101) XOR (110) which gives the result (011) whose decimal representation is 3.
As an addition to the other answers, it's worth mentioning that the caret operator can also be used with boolean operands, and it returns true (if and only if) the operands are different:
System.out.println(true ^ true); // false
System.out.println(true ^ false); // true
System.out.println(false ^ false); // false
System.out.println(false ^ true); // true
^ = (bitwise XOR)
Description
Binary XOR Operator copies the bit if it is set in one operand but not both.
example
(A ^ B) will give 49 which is 0011 0001
In other languages like Python you can do 10**2=100, try it.
I see this comment, but don't understand it.
Get its last set bit
diff &= -diff;
I tried
int a = 3 & -3; it returns 1.
int a = 2 & -2; it returns 2.
int a = 4 & -4; it returns 4.
int a = 5 & -5; it returns 1.
The comment would be better expressed as 'Get the least significant bit set'. To understand what is going on, you need to examine how negative numbers are represented in binary. The technique is called twos complement and works by starting with the positive representation of the number; you complement each bit (i.e. 1 -> 0 and 0 -> 1). You then add 1 to this number. In the example of 12:
00001100 12
11110011 complement
00000001 binary 1
11110100 add to complement to form twos complement negative
If you now AND the original value with the negative, you get
00000100
where the only bit set corresponds to the least significant bit set in the original pattern.
As the comment said, diff & -diff returns the value of the last bit that was set on diff. For example:
diff = 14
.... = 1110 (binary)
.... ^ last set bit
.... 10 is the last set bit
.... 10 in decimal is 2
Another example
diff = 24
.... = 11000 (binary)
.... ^ last set bit
.... 1000 is the last set bit
.... 1000 in decimal is 8
I would recommend reading the guidelines for how to ask a well formulated question. One recommendation I can personally give is to have one sentence at the end of your question that sums up exactly what it is you want to know.
This question already has answers here:
Why are integer literals with leading zeroes interpreted strangely?
(8 answers)
Closed 6 years ago.
See the following example:
int a = 0111;
System.out.println(a);
Output: 73
Why is this happening and how can i get the exact value without conversion?
According to the Java Language Specification 3.10.1. Integer Literals, there are 4 ways to write an integer literal:
DecimalNumeral: Digit 1-9 followed by zero or more digits 0-9, or the number 0.
HexNumeral: Leading 0x followed by one or more hexadecimal digits (0-9, a-f). Not case-sensitive.
OctalNumeral: Digit 0 followed by one or more digits 0-7.
BinaryNumeral: Leading 0b followed by one or more digits 0 or 1. Not case-sensitive.
(All 4 allow underscores for clarity)
As you can see, the number 111 depends on the prefix:
0111 (OctalNumeral) is 1*8*8 + 1*8 + 1 = 64+8+1 = 73.
111 (DecimalNumeral) is 1*10*10 + 1*10 + 1 = 100+10+1 = 111.
0b111 (BinaryNumeral) is 1*2*2 + 1*2 + 1 = 4+2+1 = 7.
0x111 (HexNumeral) is 1*16*16 + 1*16 + 1 = 256+16+1 = 273.
Which one is right depends on what you wanted.
Well you're getting the precise value. The problem is the format.
0111
gets interpreted as octal value in java. So your value actually is 73 as a quick calculation would show.
A octal value in java is defined this way:
OctalNumeral:
0 OctalDigits
0 Underscores OctalDigits
jls 3.10.1
So 0_111 would be interpreted in the same way.
The format to use in java code would be:
0b111
Which actually gets interpreted as 7 - in binary format - , as expected.
I'll add the links later on, I'm in a bit of a hurry.
This question already has answers here:
java bit manipulation
(5 answers)
Closed 8 years ago.
I am working on implementing an 8-bit adder abstracted with code in Java. This 8-bit adder is built from 8 full adder circuits. For those who don't know what a full adder is, it's a circuit that computes the sum of 2 bits.
My intention was8-bit to use a for loop to add each corresponding bit of the adders 2, 8-bit inputs such that a new bit of the 8-bit result is computed each time the for loop iterates.
Would it be possible to store the new computed bit of each iteration in a variable holding the 8-bit result using bit shifting?
Here's an example to help explain what I am asking. The bold bit would be the one that is shifted into the int holding the result.
0b00001010
+
0b00001011
First Iteration (addition starting w/ LSB)
Sum: 1
Result: 0b00000001
Carry: 0
Second Iteration
Sum: 0
Result: 0b00000001
Carry: 1
Third Iteration
Sum: 1
Result: 0b00000101
Carry: 0
Fourth Iteration
Sum: 0
Result: 0b00000101
Carry: 1
Fifth Iteration
Sum: 1
Result: 0b00010101
Carry: 0
Sixth, Seventh, Eigth Iteration
Sum: 0, 0, 0 respectively
Result: 0b00010101
Carry: 0, 0, 0 respectively
The shift operators in java are : >>>, << and >> , e.g.
System.out.println(1 << 1); // print 2
System.out.println(1 << 2); // print 4
You can't insert 1 from thin air with shifting. To insert 1 try bitwise operators: | and &
If you want to get that exact sequence, you can do it with this operation:
n = (n<<1 | (1&~n));
Starting from n=0, this gives 0b00000001, 0b00000010, 0b00000101, 0b00001010 etc.
refred already mentioned the shift operations.
shift operations are in particular useful when you are creating a bit mask (so lets say 1 bit of the whole number is set, or when a consecutive amount of bits within a bit field should be set.
Remember that
a = a << 1 is equal to
a = a*2 or a*=2 respectively.
And in anology
a = a >> 2 is equal to
a = a/2 or a/= 2
Now whenever you don't have consecutive amounts of bits that should be set you have to use binary operations like & and |.
So since you will need binary operations anyway, it does not make that much sense to use shift operations in every case because you could simple write down the hex value. But it would be possible. I made several steps to make this clear:
int a = 1; //0b00000001
a <<= 2 //0b00000100
a |= 1 //0b00000101
a <<= 1 //0b00001010
For example:
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK|
PowerManager.ACQUIRE_CAUSES_WAKEUP|PowerManager.ON_AFTER_RELEASE, "Alarm");
What does the ' | ' character mean?
More details about the problem:
I'm asking this because when I instantiate the wakelock with only PowerManager.AQUIRE_CAUSES_WAKEUP the program stops working, where as when I use the way above, it works fine.
I'm wondering if the cause of this is because the program ignore the ACQUIRE_CAUSES_WAKEUP tag and it ends up not being used.
The | is a bitwise or, and it goes beyond Android. It is often used to stuff multiple options into one parameter.
So a function of the form f(X|Y|Z) means the function should use options X, Y and Z. Of course, X, Y and Z should be appropriately coded to ensure | will preserve their values.
From the doc
bitwise inclusive OR => |
The Bitwise inclusive OR ( | ) operator performs the bitwise inclusive OR operation on each parallel pair of bits of two operands. In each pair, the result is 1, if either first or second bit is 1 (or both are 1). Otherwise the result is 0. Lets see the table of using inclusive operations.
Lets understand the inclusive OR operations using truth table:
(OR)
A B Result
0 0 0
1 0 1
0 1 1
1 1 1
If you look at constants most often used with | in the type of example you've shown, their values are powers of 2. For example:
Options.OPTION1 = 1;
Options.OPTION2 = 2;
Options.OPTION3 = 4;
Options.OPTION4 = 8;
In binary (Note I have omitted the 0b prefix for ease of reading):
Options.OPTION1 = 0001;
Options.OPTION2 = 0010;
Options.OPTION3 = 0100;
Options.OPTION4 = 1000;
If you OR Options.OPTION1 and Options.OPTION3, the result is 0101;
Options.OPTION1 | Options.OPTION3 => 0101
This enables you to pack multiple values into one since each combination of options is unique.
You can "extract" the options from the packed value by ANDing the options:
packedValue = Options.OPTION1 | Options.OPTION3;
packedValue & Options.OPTION3 => true;
packedValue & Options.OPTION4 => false;
Since
0101 AND 0100 => 0100 => true
and
0101 AND 1000 => 0000 => false
In general, that symbol (|) is a bitwise OR. It's used in a lot of different languages and environments outside of Android.
It's usage is:
"X|Y : if X or Y is 1, then the result is 1"
In your specific case it's being used to create a bit field. Besure to review the Android power manager code base here.
Possible flags for this API are:
PARTIAL_WAKE_LOCK = 0x01
SCREEN_DIM_WAKE_LOCK = 0x06
SCREEN_BRIGHT_WAKE_LOCK = 0x0a
FULL_WAKE_LOCK = 0x1a
These are mutually exclusive (you can only pick one), but you can "OR in" some other flags:
ON_AFTER_RELEASE = 0x20000000
ACQUIRE_CAUSES_WAKEUP = 0x10000000
So once your code runs it ORs these flags together resulting in:
0x20000000
| 0x10000000
| 0x0000001a
---------------
0x3000001a
I'm asking this because when i instantiate the wakelock with only "PowerManager.AQUIRE_CAUSES_WAKEUP" the program stops working
That's because you have to pick one of the levels of wake lock (PARTIAL, SCREEN_DIM, SCREEN_BRIGHT, or FULL), you're trying to run with just one of the optional wake lock flags...