Bitwise version of finding RGB in java

爷,独闯天下 提交于 2019-12-07 17:32:04

问题


I have the following method that gets a rgb value and classifies it using a smaller palette:

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 );
    }

The code that annoys me is

red = red - ( red % nrColors );
green = green - ( green % nrColors );
blue = blue - ( blue % nrColors );

I am sure there is an alternate bitwise version of it that will perform faster, but as my bitwise arithmetic is a bit rusty, I have trouble finding such an expression. Any help or comments would be appreciated.


回答1:


If nrColors is always a power of 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 );
}


来源:https://stackoverflow.com/questions/4783529/bitwise-version-of-finding-rgb-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!