我有以下方法获取rgb值并使用较小的调色板对其进行分类:
private static int roundToNearestColor( int rgb, int nrColors )
{
int red = ( rgb >> 16 ) & 0xFF;
int green = ( rgb >> 8 ) & 0xFF;
int blue = ( rgb & 0xFF );
red = red - ( red % nrColors );
green = green - ( green % nrColors );
blue = blue - ( blue % nrColors );
return 0xFF000000 | ( red << 16 ) | ( green << 8 ) | ( blue );
}
令我恼火的代码是
red = red - ( red % nrColors );
green = green - ( green % nrColors );
blue = blue - ( blue % nrColors );
我相信有一个替代的按位版本,它将执行得更快,但由于我的按位算法有点生疏,我有困难找到这样的表达式。任何帮助或意见将不胜感激。
最佳答案
如果nrColors
总是2的幂:
private static int roundToNearestColor( int rgb, int nrColors )
{
if (Integer.bitCount(nrColors) != 1) {
throw new IllegalArgumentException("nrColors must be a power of two");
}
int mask = 0xFF & (-1 << Integer.numberOfTrailingZeros(nrColors));
int red = ( rgb >> 16 ) & mask;
int green = ( rgb >> 8 ) & mask;
int blue = ( rgb & mask );
return 0xFF000000 | ( red << 16 ) | ( green << 8 ) | ( blue );
}
关于java - 在Java中查找RGB的按位版本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4783529/