This question already has answers here:
How do shift operators work in Java? [duplicate]
(9 answers)
Closed 4 years ago.
Output is 20 but i am not getting the logic behind this.Please anyone explain
public static void main(String[] args)
{
System.out.println(5<<2);
}
If you read about Bitwise and Bit Shift Operators:-
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise | operator performs a bitwise inclusive OR operation.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
// prints "2"
System.out.println(val & bitmask);
}
}
Related
We are asked to use for int variables to make the answer equal 20. We are only supposed to change the placement of the plus's and minuses. They have a minus in front of int a. Does that make int a negative?
I've googled the answer but my Googlefu isn't up to par.
public static int a = 1;
public static int b = 3;
public static int c = 9;
public static int d = 27;
public static void main(String[] args) {
int result = - a + b - c + d;
}
In the expression:
- a + b - c + d
there are 3 different operators, going left to right:
Unary minus operator
Binary plus operator
Binary minus operator
(Binary plus operator again)
In general, unary operators have higher precedence than binary operators, so this expression is equivalent to:
(( (- a) + b) - c) + d
So, the unary - applies to the a. From the linked specification above:
At run time, the value of the unary minus expression is the arithmetic negation of the promoted value of the operand.
So, it doesn't make a negative, it results in an expression whose value is the negation of a. This happens to be negative, because a has a positive value. However, it doesn't make a anything, a is left unchanged.
The only way to actually make a negative would be to reassign it:
a = -Math.abs(a);
For a more elaborate answer please have a look at the java language specification, where you can find detailed information on how operators and expressions are evaluated in java (in your case: https://docs.oracle.com/javase/specs/jls/se12/html/jls-15.html#jls-15.15.4)
This question already has answers here:
Explain the use of a bit vector for determining if all characters are unique
(12 answers)
Closed 4 years ago.
I have the following code that finds unique characters in a string using bit vectors. We assume it's an ASCII char set with lower case letters only.
I am having a hard time understanding the use of bit vectors below. Even after debugging through the program and following the changes variables go through after each loop.
// assuming that the characters range from a-z
static boolean isUniqueBitVector(String str) {
int checker = 0;
for(int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
if((checker & (1 << val)) > 0) {
return false;
} else {
checker |= (1 << val);
}
}
return true;
}
What's the purpose of left shifting the val(int representation of each char in string) by 1 and AND'ing it with checker (initialized to 0) and OR'ing it in the else block.
checker is a 32 bit integer, of which we assign the lowest 26 to store a flag for each letter a-z. We can use bits for this because a letter can be non-unique only once.
int val = str.charAt(i) - 'a'; computes the index of the bit that corresponds to the current letter. This is where the assumption that the input only contains a-z comes in. val will be a number between zero and 25.
In general, (1 << val) is the bit corresponding to the selected letter. << is the left shift operator. It is used to move 1, which only has a single bit on, val positions to the left. So for example, 1<<3 would be 8. In fact, left shifting is equivalent to multiplying by a power of 2.
(checker & (1 << val)) verifies if the selected bit is on or not. The & operator is called bitwise and. It combines two numbers and sets any bits that are on in both to on. Remember that 1 << val only has a single bit turned on. The only way the result of that and checker is going to be nonzero is if checker already has the same bit turned on. In that case we return false because a letter has been repeated.
In the case that a new letter has been found, we need to turn on the correct bit in checker. This is what checker |= (1 << val); does. The bitwise or operator, |, turns on a bit in the result if it is on in either operand. Again, 1 << val has only one bit on. Therefore the result of the or is to replicate checker and turn on that one bit (whether or not it was already on).
All of the operations you see here are very common idioms. Hopefully my explanation has helped you in some way, because you will almost certainly see very similar things in any simple bit twiddling code.
I have to write a method which converts an int value to the same negative int value. For example, if the user types in 5 the method should give back -5.
The whole story is:
The method has a transfer parameter which is either a positive or a negative int. Is it a positive int, we should change it to a negative int. If it is a negative int, do nothing.
It is also hard to check if the given int is positive or negative.
The regulations:
I'm only allowed to use the arithmetic operation + and all the boolean operations. But in this case I know that I have to use XOR.
It's not about writing the method and all the JAVA stuff. It's just the logic I struggle with.
How can I change a value to its negative value using only XOR and +?
ATTENTION:
The only operations allowed are:
!
^
&&
||
+
No *, no -, no ~
Edit:
The two solutions from CherryDT and MikeC are working well. Any ideas how to check if its a negative or a positive parameter with the same regulations? I thought this would be the easy part. Then realized it isn't.
(x ^ -1) + 1
Explanation: Basically, it's the same as ~x + 1. -1 has all bits set, and therefore inverts all bits when XORed with, just like NOT. And since, the other way round, inverting will always give you -x - 1, all you need to do is invert and add 1.
Here we go
public class Test {
public static void main(String []args){
int x = 245;
System.out.println(x);
x = (~x^x)*x;
System.out.println(x);
}
}
This question already has answers here:
What is the purpose of Java's unary plus operator?
(7 answers)
Closed 8 years ago.
I ran across this while reviewing a colleague's code. She'd left it in by accident (it used to be a String concatenation), and I assumed that it wouldn't compile. Turns out I was wrong, so I tried seeing what that operator did:
public static void main(String[] args) {
int i = -1;
System.out.println(String.format("%s", +i));
System.out.println(String.format("%s", +i));
}
As far as I can tell, it does nothing, but I'm curious if there is a reason it's allowed to compile. Is there some hidden functionality to this operator? It's similar to ++i, but you'd think the compiler would barf on +i.
That is the plus unary operator +. It basicaly it does numeric promotion, so "if the operand is of compile-time type byte, short, or char, it is promoted to a value of type int".
Another unary operator is the increment operator ++, which increments a value by 1. The increment operator can be applied before (prefix operator) or after (postfix operator) the operand. The difference is that the prefix operator (++i) evaluates to the incremented value, whereas the postfix operator (i++) evaluates to the original value.
int i = -1;
System.out.println(+i); // prints -1
System.out.println(i++); // prints -1, then i is incremented to 0
System.out.println(++i); // i is incremented to 1, prints 1
Suppose code is given like this:
pattern_mask[pattern[i]] &= ~(1UL << i);
What kind of type is this in Java? How do I implement this in Java?
Java does not have unsigned long, but 1L is a 64-bit signed long literal.
References
JLS 4.2.1 Integral Types and Values
For long, from -9223372036854775808 to 9223372036854775807, inclusive
JLS 3.10.1 Integer Literals
An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int. The suffix L is preferred, because the letter l (ell) is often hard to distinguish from the digit 1 (one).
On masking of count operand
The shift count is masked: only lower 5-bits for int shift, and only lower 6-bits for long shift.
The following snippet shows how due to this, shifting on 1 is different from shifting on 1L.
System.out.println(1 << 1); // prints "2"
System.out.println(1 << 33); // prints "2"
System.out.println(1L << 33); // prints "8589934592"
System.out.println(1L << 65); // prints "2"
Related questions
What’s the reason high-level languages like C#/Java mask the bit shift count operand?