It is a bit shift operation. Read more here. It will pack these 3 numbers into one integer.
understanding java operator << [duplicate]
-
12-07-2023 - |
Question
i was working through the following oracle java class and came across this line of code:
public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
I am lost as to what "<<" means, I also don't know what the return statement is suppose to return
Solution
OTHER TIPS
24 bit colors are often represented as RRRRRRRRGGGGGGGGBBBBBBBB, with 8 bit values for each color. Your code takes the red value, shifts it 16 bits, shifts the green value 8 bits, and keeps the blue value unshifted, then performs a logical OR, which in this case is the same as adding the values. Think of it this way:
Your byte values for each color:
Red = 00011010
Green = 10101010
Blue = 11111111
The shifted values become:
Red << 16 =
00011010 00000000 00000000
Green << 8 =
00000000 10101010 00000000
Blue =
00000000 00000000 11111111
The logical OR combines them into:
00011010 10101010 11111111
which is your 24 bit RGB value, which is returned.
public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
I am lost as to what "<<" means, I also don't know what the return statement is suppose to return?
First off, the '<<' is called a bit shift operator. There is a fantastic write-up about them located here.
As to your second question, look at the signature of the method... it's going to return an int
. BUT, in this case, it is going to return and int
containing the value of blue
and the bit shifted values of red
and green
.
Hope this helps!
x << y
means "shift binary representation of x
to left y
places"
For instance
System.out.println(4 << 2);
will print 16
.
4
is 100
in binary. If you shift 100
to the left 2 places, you get 10000
which is 16
in decimal.