What does << mean in Java?
I can't find out what <<
means in Java because I can't search for it on Google - I am absolutely lost!
The code in question is:
public int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
It's taken from: http://java.sun.com/docs/books/tutorial/essential/concurrency/example/ImmutableRGB.java
I would really appreciate s开发者_运维问答omeone telling me, thanks!
Left shift of the bits
If red == 4 (which in binary is: 00000100) then red << 16 will insert sixteen 0-bits at its right, yielding: 000001000000000000000000 which is 262144 in decimal
Q. What is this?
A. An "operator"
Q. How do I get to know about operators in java?
A. Google for "Java operators"
And the result is this:
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.
Left shift a number of bits. It is equivalent to multiplying by two that many times.
It's used for setting specific bits in a byte, or specific bytes in a word.
It is the left shift operator. Here's some more information on shift operators from the Java Tutorial.
In your example code the three integer values: red, green and blue will typically have values 0-255. Hence, it is possible to combine these values and represent them as a single integer by shifting the red value by 16 bits, shifting the green value by 8 bits and then performing a bitwise-OR operation to combine the values.
its a bit shift. search for operators java
, it will return you detailed explanations.
Its a left bit shift
Its left shifting and convert Red, Green, Blue into 24 bit Number
"<<" means left shift the bits of a value.
">>" means right shift the bits of a value.
example:
int a = 5; //the binary value of 5 is 101
a = a << 3; //left shift 3 bits on 101, 101 000<< add 3 bits(0) on the right, become '101000'
System.out.println(a); //this will display 40, the decimal for '101000'
int b = 9; //the binary value of 8 is 1001
b = b >> 3; //right shift 3 bits on >>000 1001 add 3 bits(0) on the left, truncate the last 3 bits on the right become '001'
System.out.println(b); //this will display 1, the decimal for '001'
精彩评论