Representation of Integers at a Bit Level in Java – Java 中整数位级的表示方法

最后修改: 2024年 3月 19日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Java stores numbers in memory as binary. Understanding how integers are represented at the bit level can help us with certain operations.
In this tutorial, we’ll look at some of the specifics of number representation in Java, and see how Java’s bitwise operations work.

2. Bitwise Operations in Java

2.Java 中的位操作

In Java, integers are represented using 32 bits, and long integers use 64 bits. It’s important to note that Java uses 2’s complement representation for negative numbers. In this case, where the first bit is 1, the number is assumed to be negative. Negative numbers are calculated by taking the number, flipping all 1’s and 0’s, and then adding 1.

在 Java 中,整数使用 32 位表示,长整数使用 64 位表示。值得注意的是,Java 对负数使用2 的补码表示。在这种情况下,当第一位为 1 时,数字被假定为负数。负数的计算方法是:取数,翻转所有 1 和 0,然后加 1。

For example, in eight bits, the number 6 is 0b00000110. To convert this to -6, we invert it to 0b11111001 and then, add one, so it becomes 0b11111010.

例如,数字 6 的八位数是 0b00000110 。要将其转换为-6,我们将其反转为0b11111001,然后加一,这样就变成了0b11111010.

Furthermore, bitwise operations lay a great foundation for several use cases as they are often quicker for the CPU that full mathematical or logical expressions.

此外, 位运算为多个使用案例奠定了坚实的基础,因为对于 CPU 而言,位运算通常比完整的数学或逻辑表达式更快。

2.1. AND Operator (&)

2.1.AND 运算符 (&)

The AND operator (&) performs a bitwise AND operation between two 32-bit integers:

AND 运算符 (&) 在两个 32 位整数之间执行按位 AND 运算:

int result = 0b1100 & 0b0111;
assertEquals(0b0100, result);

This operation evaluates each bit’s position independently. If both corresponding bits in the operands are 1, the result will have a 1 at that position; otherwise, it will be 0. In the provided example:

此操作会独立评估每个位的位置。如果操作数中的两个相应位都为 1,则结果在该位置上将为 1;否则,结果将为 0:

  • Binary representation of 12 (0b1100)
  • Binary representation of 7 (0b0111)
  • Bitwise AND operation yields 0b0100
  • Resulting in the decimal value 4

2.2. OR Operator (|)

2.2 OR 运算符 (|)

The OR operator (|) does a bitwise OR operation on the same-position bits of two numbers:

OR 运算符 (|) 对两个数的相同位置位进行位操作 OR 运算:

int result = 0b1100 | 0b0111;
assertEquals(0b1111, result);

Similar to the AND operator, the OR operator compares each bit position. If at least one of the corresponding bits in the operands is 1, the result will have a 1 at that position. In this example, the result is 0b1111, equivalent to the decimal value 15.

与 AND 运算符类似,OR 运算符也比较每个位的位置。如果操作数中至少有一个相应的比特位为 1,则结果在该位置上将为 1。在本例中,结果为 0b1111,相当于十进制值 15。

2.3. XOR Operator (^)

2.3. XOR 运算符 (^)

We can use the XOR operator (^) in a bitwise XOR operation in which the corresponding bits are operated on each other:

我们可以使用 XOR 运算符 (^)进行比特 XOR 运算,在这种运算中,相应的比特相互操作:

int result = 0b1100 ^ 0b0111;
assertEquals(0b1011, result);

This operation sets the result bit to 1 if the corresponding bits in the operands differ. In the provided example, the result is 0b1011, corresponding to the decimal value 11.

如果操作数中的相应位不同,该操作会将结果位设为 1。在示例中,结果位为 0b1011,对应十进制值 11。

2.4. Bitwise NOT (~)

2.4.位运算 NOT (~)

The bitwise NOT operator (~) inverts the bits of its operand, turning 1s into 0s and vice versa:

位操作 NOT 运算符(~)可以反转操作数的位,将 1 变为 0,反之亦然:

int result = ~0b0101;
assertEquals(-0b0110, result);

Each bit is inverted, transforming 0s into 1s and vice versa. Moreover, the result is -0b0110, equivalent to the decimal value -6 using two’s complement representation.

每个比特都被反转,将 0 转换为 1,反之亦然。此外,结果是 -0b0110,相当于使用 两进制表示的十进制值 -6

2.5. Left Shift (<<) and Right Shift (>>)

2.5.左移 (<<) 和右移 (>>)

The left shift (<<) operator shifts the bits of a number to the left by a specified number of positions:

左移(<<)运算符将数字的位向左移动指定的位数:

int result = 0b0101 << 2;
assertEquals(0b10100, result);

Here, we perform a bitwise left shift operation on the value stored in variable a. Furthermore, this operation shifts the binary representation of two positions to the left, padding the vacated positions on the right with zeros.

在这里,我们对存储在变量 a 中的值执行位左移操作。此外,该操作会将二进制表示向左移动两个位置,并在右侧空出的位置填充 0。

Similarly, the right shift (>>) operator shifts the bits to the right:

同样,右移(>>)运算符会将位向右移动:

int result = 0b0101 >> 1;
assertEquals(0b10, result);

Conversely, we perform a bitwise right shift operation by shifting the binary representation of the variable a one position to the right. The vacated position on the left is filled based on the sign bit for signed integers. So positive numbers stay positive and negative numbers stay negative.

相反,我们通过将变量 a 的二进制表示向右移动一个位置,来执行位向右移动操作。左边空出的位置将根据有符号整数的符号位进行填充。因此,正数保持为正,负数保持为负。

3. Use Case: Color Modification Using Bitwise Operations

3.用例:使用比特运算修改颜色

In this practical example, we’ll explore how we can apply bitwise operations to modify the color of an RGB value.

在本示例中,我们将探讨如何应用位操作来修改 RGB 值的颜色。

3.1. Original Colors and Masks

3.1.原色和蒙版

int originalColor = 0xFF336699;
int alphaMask = 0xFF000000;
int redMask = 0x00FF0000;
int greenMask = 0x0000FF00;
int blueMask = 0x000000FF;

Here, we initialize the original color as 0xFF336699, a hexadecimal representation of an RGB color. Additionally, four masks (alphaMask, redMask, greenMask, and blueMask) are defined to extract individual color components based on their bit positions.

在这里,我们将原始颜色初始化为 0xFF336699,这是 RGB 颜色的十六进制表示。此外,我们还定义了四个掩码(alphaMaskredMaskgreenMaskblueMask),以根据位位置提取单个颜色成分。

3.2. Extracting Color Components

3.2.提取颜色成分

int alpha = (originalColor & alphaMask) >>> 24;
int red = (originalColor & redMask) >>> 16;
int green = (originalColor & greenMask) >>> 8;
int blue = originalColor & blueMask;

We extract the alpha, red, green, and blue components using bitwise AND operations with their respective masks. Then, we apply the right shift (>>>) to align the extracted bits to the least significant bit (LSB) position.

我们使用比特 AND 运算和各自的掩码提取 α, red, greenblue 元件。然后,我们应用右移 (>>>),将提取的比特对齐到最小有效位 (LSB) 位置。

  • The alpha component, extracted by (originalColor & alphaMask) >>> 24, results in 1111 1111 in binary
  • The red component, extracted by (originalColor & redMask) >>> 16, is 0011 0011 in binary
  • The green component, extracted by (originalColor & greenMask) >>> 8, is 0110 1001 in binary
  • The blue component, extracted by originalColor & blueMask, is 1001 1001 in binary

3.3. Modifying Color Components

3.3.修改颜色组件

red = Math.min(255, red + 50);
green = Math.min(255, green + 30);

Next, we modified the red and green components, simulating a color adjustment. Moreover, we perform the modification while ensuring that the values don’t exceed the maximum of 255.

接下来,我们修改了红色绿色部分,模拟了颜色调整。此外,在进行修改时,我们还要确保数值不超过 255 的最大值。

  • The red component is modified using red = Math.min(255, red + 50), resulting in 0100 0010 in binary
  • The green component is modified using green = Math.min(255, green + 30), resulting in 0111 1111 in binary

3.4. Recreating Modified Color

3.4.重现修改过的颜色

int modifiedColor = (alpha << 24) | (red << 16) | (green << 8) | blue;

Furthermore, we combine the modified alpha, red, green, and blue components using bitwise OR (|) and left shift (<<) operations to recreate the modified color.

此外,我们还使用位操作 OR (|) 和左移 (<<) 将修改后的阿尔法、红色、绿色和蓝色分量组合起来,重新创建修改后的颜色。

The reconstructed color is calculated as modifiedColor = (alpha << 24) | (red << 16) | (green << 8) | blue, resulting in 1111 1111 0010 0010 1101 0110 1001 in binary.

重建颜色的计算公式为 modifiedColor = (alpha << 24) | (red << 16) | (green << 8) | blue,结果为二进制 1111 1111 0010 0010 1101 0110 1001。

4. Conclusion

4.结论

In this article we looked at how Java represents numbers in memory. We looked at the binary representation and how to use it to understand bitwise operations.

在本文中,我们介绍了 Java 如何在内存中表示数字。我们了解了二进制表示法以及如何使用它来理解位操作。

Finally, we looked at a way that masks and bit shifting can be useful in a real-world example.

最后,我们来看一个实际例子,看看掩码和位移如何发挥作用。

As always, the complete code samples for this article can be found over on GitHub.

与往常一样,本文的完整代码示例可在 GitHub 上找到