Java: 0b1000_1100_1010 中这样的数字是什么意思? (数字之间的"b")

What does a number like this mean in Java: 0b1000_1100_1010? (The "b" between the numbers)

我正在练习 Java 课程的一些任务,我遇到了这个变量

int x = 0b1000_1100_1010;

我知道数字旁边的 "f" 和 "d" 表示数字是 floatdouble,分别。但是这个"b"之间呢?

我看到here这与bytes有关,但我不太明白它是如何工作的。

我的问题也适用于我刚刚在 link 上看到的数字之间的 "x"。

谢谢!

这是binary literal.

这是一种表示数字用二进制表示的符号。

这就像你使用十六进制表示法:0xF9。在Java中,可以用0b1111_1001表示相同的数,即十进制249。

字节无关,与位有关。您可以清楚地看到哪些位已设置,哪些未设置。默认情况下,以 0b 开头的数字是 int,但您可以像这样写 0b1010L(注意尾随 L)。

b可以是小写也可以是大写。所以这也是有效的:0B1111。请注意,由于 0b 前缀表示二进制表示,因此不允许使用 01 以外的任何字符(以及 _ 来标记分隔)。

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).

The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

Java 允许您在 int 值中使用 _,如下所示:

public class Main {
    public static void main(String[] args) {
        int x = 1_2_3;
        System.out.println(x + 100);
    }
}

输出:

223