How does Java handle arguments separated by | ?
for example
private void foo(int i) {
System.out.println(i);
}
private void bar() {
foo(1 | 2 | 1);
}
Which would give the output
3
I've seen this used in SWT/JFace widget constructors. What I can't figure out is how the value of i is decided.
The | is a bitwise or-operator.
foo(1 | 2 | 1);
means call foo with the argument 1 bitwise-or 2 bitwise-or 1.
1 in binary is 01
2 in binary is 10
Bitwise or of 01 and 10 is 11 which is 3 in decimal.
Note that the | operator can be used for booleans as well. Difference from the || operator being that the second operand is evaluated even if the first operand evaluates to true.
Actually, all bitwise operators work on booleans as well, including the xor ^. Here however, there are no corresponding logical operator. (It would be redundant, since there is no way of doing a "lazy" evaluation of ^ :)
it is using the bitwise OR operator. For starters, 1 | 1 = 1 so the second 1 is redundant. If we remove the redundant 1 we are left with the equation 1 | 2 = 3. Looking at it in 2 bit binary it looks like:
01 | 10 = 11
The or operator will match up the corresponding bits from each or the values and if there is one 1 in either or both values for a given position, the result is a 1. If both values for both the corresponding bits then the result is 0.
Related
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 have found this line in an application source code but i cant figure out the meaning of the bitwise or inclusive operator "|" between the two flags.
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
I did not also understand the meaning of this operator |= in the following line:
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Someone could help me plz.
I'd started my answer while no-one else had answered, so I decided to finish it anyway...
The pipe and ampersand | and & perform the OR and AND operations respectively.
You'll be used to seeing || and &&, which perform the boolean logic OR and AND, and the use of a single | or & is a bitwise operation.
If you look on the flag documentation, the flag for clear_top is 0x04000000, and single_top is 0x20000000.
The operation which you are performing is therefore:
0x04000000 OR 0x20000000 = 0x24000000
Which sets the required bits in the intent to use both of the desired flags.
The a |= b operator is the overloaded equivalent of a = a | b, similar to the usage of +=, -- or ++, which you should be used to seeing elsewhere
a | b is bitwise OR of a and b.
Its the Assignment by bitwise OR
a1 |= a2;
is short for:
a1 = a1 | a2;
|= reads the same way as +=.
Let's for assume for example that FLAG_ACTIVITY_CLEAR_TOP is 2 and FLAG_ACTIVITY_SINGLE_TOP is 4.
So in binnary the represantion will be 0000000010 for the decimal value 2 and 00000100 for the value 4. The binary or operation between those two values will give the value 6 : 00000110 (The on bits on both 2 and 4 are on) . using power of two values for suck constants will make sure thatonly unique values will come out after th bitwise or:
For example : 1 is 00000001 2 is 00000010 4 is 00000100 8 is 00001000 16 is 00010000 .....
If you are settings flags this way- it's very easy to decode the original flags : just perform a bitwise AND operation with the original flag , if it's zero than the flag is not there - if it's the flag itself - then the flag is up.
For example : let's check 000011000 for the flag SOME_FLAG - and let's say for the porpuse of the example that it's value is 8 - 00001000. After the bitwise and operation : 00011000 & 00001000 - We will get 00001000 , ANDing with something else (that does not include the flag SOME_FLAG - like any other flag with a power of 2 value) will return 0.
It's the same as notification.flags = (notification.flags | Notification.FLAG_AUTO_CANCEL);
cf. a += b is equivalent to a = (a + b);
where I've used the superfluous parentheses for clarity.
As far as I know, these are bit operators.
As Bathsheba wrote, it's equal to (notification.flags | Notification.FLAG_AUTO_CANCEL);
It's an logical or, for informations see here: Oracle.com
Infos about or at Wikipedia.
If you look at those flags, you will see they are all powers of two. This means exactly one bit is set to 1, so performing a bitwise or in this case does just mean to set all those flags.
I am very confused on right shift operation on negative number, here is the code.
int n = -15;
System.out.println(Integer.toBinaryString(n));
int mask = n >> 31;
System.out.println(Integer.toBinaryString(mask));
And the result is:
11111111111111111111111111110001
11111111111111111111111111111111
Why right shifting a negative number by 31 not 1 (the sign bit)?
Because in Java there are no unsigned datatypes, there are two types of right shifts: arithmetic shift >> and logical shift >>>. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
Arithmetic shift >> will keep the sign bit.
Unsigned shift >>> will not keep the sign bit (thus filling 0s).
(images from Wikipedia)
By the way, both arithmetic left shift and logical left shift have the same result, so there is only one left shift <<.
Operator >> called Signed right shift, shift all the bits to right a specified number of times. Important is >> fills leftmost sign bit (Most Significant Bit MSB) to leftmost bit the after shift. This is called sign extension and serves to preserve the sign of negative numbers when you shift them right.
Below is my diagrammatic representation with an example to show how this works (for one byte):
Example:
i = -5 >> 3; shift bits right three time
Five in two's complement form is 1111 1011
Memory Representation:
MSB
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
7 6 5 4 3 2 1 0
^ This seventh, the left most bit is SIGN bit
And below is, how >> works? When you do -5 >> 3
this 3 bits are shifted
out and loss
MSB (___________)
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
| \ \
| ------------| ----------|
| | |
▼ ▼ ▼
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
+----+----+----+---+---+---+---+---+
(______________)
The sign is
propagated
Notice: the left most three bits are one because on each shift sign bit is preserved and each bit is right too. I have written The sign is propagated because all this three bits are because of sign(but not data).
Also because of three right shift right most three bits are losses out.
The bits between right two arrows are exposed from previous bits in -5.
I think it would be good if I write an example for a positive number too. Next example is 5 >> 3 and five is one byte is 0000 0101
this 3 bits are shifted
out and loss
MSB (___________)
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
+----+----+----+---+---+---+---+---+
| \ \
| ------------| ----------|
| | |
▼ ▼ ▼
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
+----+----+----+---+---+---+---+---+
(______________)
The sign is
propagated
See again I writes The sign is propagated, So leftmost three zeros are due to sign bit.
So this is what operator >> Signed right shift do, preserves the sign of left operand.
[your answer]
In your code, you shifts -15 to right for 31 times using >> operator so your right most 31 bits are loosed and results is all bits 1 that is actually -1 in magnitude.
Do you notice that In this way -1 >> n is equivalent to not a statement.
I believe if one do i = -1 >> n it should be optimized to i = -1 by Java compilers, but that is different matter
Next, It would be interesting to know in Java one more right shift operator is available >>> called Unsigned Right Shift. And it works logically and fills zero from left for each shift operation. So at each right shift you always get a Zero bit on left most position if you use unsigned right shift >>> operator for both Negative and Positive numbers.
Example:
i = -5 >>> 3; Unsigned shift bits right three time
And below is my diagram that demonstrates how expression -5 >>> 3 works?
this 3 bits are shifted
out and loss
MSB (___________)
+----+----+----+---+---+---+---+---+
| 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 |
+----+----+----+---+---+---+---+---+
| \ \
| ------------| ----------|
| | |
▼ ▼ ▼
+----+----+----+---+---+---+---+---+
| 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 |
+----+----+----+---+---+---+---+---+
(______________)
These zeros
are inserted
And you can notice: this time I am not writing that sign bits propagated but actually >>> operator insert zeros. Hence >>> doesn't preserves sign instead do logical right shift.
In my knowledge unsigned right shift is useful in VDU (Graphics programming),Although I haven't used it but read it some where in past.
I would suggest you read this: Difference between >>> and >> : >> is arithmetic shift right, >>> is logical shift right.
Edit:
Some interesting about Unsigned Right Shift Operator >>> operator.
The unsigned right shift operator >>> produces a pure value that is its left operand right-shifted with zero 0 extension by the number of bits specified by its right operand.
Like >> and <<, operator >>> also operator never throws an exception.
The type of each operand of the unsigned right shift operator must be an integer data type, or a compile-time error occurs.
The >>> operator may perform type conversions on its operands; unlike arithmetic binary operators, each operand is converted independently. If the type of an operand is byte, short, or char, that operand is converted to an int before the value of the operator is computed.
The type of the value produced by the unsigned right shift operator is the type of its left operand. LEFT_OPERAND >>> RHIGT_OPERAND
If the converted type of the left operand is int, only the five least significant bits of the value of the right operand are used as the shift distance. (that is 25 = 32 bits = number of bit in int)
So, the shift distance is in the range 0 through 31.
Here, the value produced by r >>> s is the same as:
s==0 ? r : (r >> s) & ~(-1<<(32-s))
If the type of the left operand is long, then only the six least significant bits of the value of the right operand are used as the shift distance.(that is 25 = 64 bits = number of bit in long)
Here, the value produced by r >>> s is the same as the following:
s==0 ? r : (r >> s) & ~(-1<<(64-s))
A Interesting Reference: [Chapter 4] 4.7 Shift Operators
Because >> is defined as an arithmetic right shift, which preserves the sign. To get the effect you expect, use a logical right shift, the >>> operator.
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...
I am extending a tool in Java that somehow is capable of applying Logical (AND, OR and XOR) over three Long values.
How is that possible? If it is possible?
You can apply bit-wise operators on longs:
& is AND
| is OR
^ is XOR
Maybe they wanted to implement IDL-like logical operators
Default Definitions of True and False
Data Type True False
====================================================================================
Byte,integer, and long Odd integers Zero or even integers
Floating point and complex Non-zero values Zero
String Any string with non-zero length Null string (" ")
Heap variables Non-null values Null values
What do you mean by not possible? 3 | 4 | 5 is a perfectly valid expression as 3 & 4 & 5.