Java 按位除法?(更改ints的格式)

Java 按位除法?(更改ints的格式),java,colors,bit-manipulation,Java,Colors,Bit Manipulation,我正在使用Java。我有一个整数,其中: 位24-31为alpha,位16-23为红色, 8-15为绿色,0-7为蓝色 我想将其更改为int,其中: 位5-7为红色,2-4为绿色,0-1为蓝色 我不知道该怎么做才是最好的。(显然,代表性颜色的某些保真度将丢失。这是可以接受的,只要它是相称的,因此颜色看起来大致相同。) 我可以进行除法吗?不可以。您需要进行位移位和掩蔽 例如,要变红,需要3位。因此,您需要获取红色的最高有效位,即位23、22和21 所以 int red=((颜色>>21)和0x07

我正在使用Java。我有一个整数,其中:

位24-31为alpha,位16-23为红色, 8-15为绿色,0-7为蓝色

我想将其更改为int,其中:

位5-7为红色,2-4为绿色,0-1为蓝色

我不知道该怎么做才是最好的。(显然,代表性颜色的某些保真度将丢失。这是可以接受的,只要它是相称的,因此颜色看起来大致相同。)


我可以进行除法吗?

不可以。您需要进行位移位和掩蔽

例如,要变红,需要3位。因此,您需要获取红色的最高有效位,即位23、22和21

所以

int red=((颜色>>21)和0x07);//获取src red的前3位,并放入int的底部

int newColor=red对于每个组件,移位位并屏蔽最低有效位

长期来看,如果
col
是您的原始颜色,则:

r = (col >> 21) & 0x07; // bits 21 - 23
g = (col >> 13) & 0x07; // bits 13 - 15
b = (col >>  6) & 0x03; // bits  6 -  7
你的新价值观是:

(r << 5) | (g << 2) | b
我建议你

int argb =
// extract the colours. 
int red = (argb >> 16) & 0xFF;
int green = (argb >> 8) & 0xFF;
int blue = argb & 0xFF;

// reduce the number of bits.
red >>= 5;
green >>= 5;
blue >>= 6;

// build the new value
int rgb2 = (red << 5) + (green << 2) + blue;
int argb=
//提取颜色。
int red=(argb>>16)和0xFF;
绿色整数=(argb>>8)&0xFF;
蓝色整数=argb&0xFF;
//减少位数。
红色>>=5;
绿色>>=5;
蓝色>>=6;
//建立新的价值观

int rgb2=(红色)
&0xFF
的目的是在进行转换之前获取所有8位。最简单的方法是删除低位(如@Alnitak所做)但是您可能希望对结果进行四舍五入或其他操作。
argb
是alpha/red/green/blue的缩写。如果您想更改此值,可以在最后一行分配它,而不是
rgb2
您应该得到233。这是我运行代码时得到的结果。-1355953是11111101011 01001111 01001111 0100111 0100111 0100111,如果您跳过第一个字节,取前3位,前3位和前2位,得到111 010 01,即233。
rgb = (col & 0xe00000) >> 16 | (col & 0xe000) >> 11 | (col & 0xc0) >> 6; 
int argb =
// extract the colours. 
int red = (argb >> 16) & 0xFF;
int green = (argb >> 8) & 0xFF;
int blue = argb & 0xFF;

// reduce the number of bits.
red >>= 5;
green >>= 5;
blue >>= 6;

// build the new value
int rgb2 = (red << 5) + (green << 2) + blue;