在Java中更改32位整数的特定位

时间:2014-01-29 00:08:05

标签: java bit-manipulation bit bitwise-operators

背景:我有一个带有二进制表示的32位整数,如下所示:

1111 1111 0000 0000 0000 0000 1111 1111

注意:这是ARGB值Color.BLUE的二进制表示。我将其用于说明目的,但它与我试图解决的情况有关。

问题:我试图改变高阶位,使其二进制表示如下所示:

1000 0000 0000 0000 0000 0000 1111 1111

或者更简单地说,前八个高阶位应该像这样改变:

1111 1111 -> 1000 0000

当前解决方案尝试:到目前为止,我已经成功地屏蔽了前8位高位,然后使用按位“或”“添加”所需的值,如下所示:< / p>

int colourBlue = Color.BLUE.getRGB(); // equal to binary value at top of question
int desiredAlpha = (0x80 << 24); // equal to 1000 0000 0000 0000 0000 0000 0000 0000

// Mask out the eight high order bits, and add in the desired alpha value
int alteredAlphaValue = (colourBlue & 0x00FFFFFF) | desiredAlpha;

虽然目前确实有效,但是从我的计算机体系结构课程开始已经有一段时间了,而且我还没有很多经验可以使用按位运算符和低级别位操作。

我的问题:我的解决方案是否是完成此任务的正确方法?如果它在某种程度上是不恰当的(或者只是简单的“哑”),那么实现改变特定位的目标的更好(或更正确)的方法是什么?

1 个答案:

答案 0 :(得分:1)

从C#转码为Java(未经测试):

public static int setBits(int orig, int newBits, int startBit, int length)
{
    int mask = Mask(startBit, length);
    return (orig & ~mask) | (bits << startBit & mask);
}

public int Mask(int startBit, int length)
{
    if (length ==32)
        return Integer.MAX_VALUE;
    else
        return (1 << (1 << length) - 1) << startbit;
}

或者,如果您愿意,您可以直接指定掩码,并避免位移:

public static int setBits(int orig, int newBits, int mask)
{
    return (orig & ~mask) | (bits & mask);

}

当然,如果您将RGB值作为32位数字传递,您可以始终convert it to a byte array,反之亦然,这使得操作变得更加容易。