在java中寻找RGB的按位版本 [英] Bitwise version of finding RGB in java

查看:114
本文介绍了在java中寻找RGB的按位版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的方法获得一个RGB值和分类它使用较小的调色板:

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

在code惹恼我是

The code that annoys me is

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

我肯定有它的一个替代版本,按位将执行速度更快,但我的按位运算是有点生疏了,我很难找到这样一个前pression。任何帮助或意见将AP preciated。

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.

推荐答案

如果 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中寻找RGB的按位版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆