我是Java的新手。我在Java教程Oracle中看到了以下代码。我很难理解这段代码的目的:
public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
我理解按位运算符是如何工作的,但我很难理解为什么getRGB()方法的编写方式。是否有另一种方法来编写getRGB()方法?
public class SynchronizedRGB {
// Values must be between 0 and 255.
private int red;
private int green;
private int blue;
private String name;
private void check(int red,
int green,
int blue) {
if (red < 0 || red > 255
|| green < 0 || green > 255
|| blue < 0 || blue > 255) {
throw new IllegalArgumentException();
}
}
public SynchronizedRGB(int red,
int green,
int blue,
String name) {
check(red, green, blue);
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}
public void set(int red,
int green,
int blue,
String name) {
check(red, green, blue);
synchronized (this) {
this.red = red;
this.green = green;
this.blue = blue;
this.name = name;
}
}
public synchronized int getRGB() {
return ((red << 16) | (green << 8) | blue);
}
public synchronized String getName() {
return name;
}
public synchronized void invert() {
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
name = "Inverse of " + name;
}
public static void main(String[] args) {
SynchronizedRGB color = new SynchronizedRGB(0, 0, 0, "Pitch black");
System.out.println(color.getRGB());
}
}
答案 0 :(得分:2)
左移位运算符<< x
相当于乘以2 ^ x,因此您可以将其写为
return ((red * 65536 ) + (green *256) + blue);
答案 1 :(得分:1)
每个组件是一个字节(8位),整数是32位,因此您可以在32位整数中存储4个8位数字,对于alpha,红色,绿色和蓝色存储8位。 &gt;&gt;或&lt;&lt;运算符是位移运算符,将数字中的位移动指定的量。 1&lt;&lt; 1结果2.看二进制序列...... 00000001&lt;&lt; 1 = 00000010