初始化 java 字节数组:可能会丢失精度

Initialize java byte array: possible loss of precision

我正在Java中初始化一个byte[],使用十六进制二进制 表示法。

当值接近一个字节的容量时,似乎没有自动转换为字节。

解决方案显式转换为 byte

$ javac bitsandbytes/ByteBufferTest.java 
bitsandbytes/ByteBufferTest.java:9: error: possible loss of precision
    static byte[] byteArray = { 0xFF, (byte) 0xCC, 0xCC, 0b1000_0000, 0x2F, 0x01 };
                                ^
  required: byte
  found:    int
bitsandbytes/ByteBufferTest.java:9: error: possible loss of precision
    static byte[] byteArray = { 0xFF, (byte) 0xCC, 0xCC, 0b1000_0000, 0x2F, 0x01 };
                                                   ^
  required: byte
  found:    int
bitsandbytes/ByteBufferTest.java:9: error: possible loss of precision
    static byte[] byteArray = { 0xFF, (byte) 0xCC, 0xCC, 0b1000_0000, 0x2F, 0x01 };
                                                         ^
  required: byte
  found:    int
3 errors

It seems that auto-casting to byte is not done when the value approaches the capacity of a byte.

不,当值超出范围时会发生。 Java 中的 byte 在 [-128, 127] 范围内。所以 0xcc 超出范围,例如......虽然这与你表达文字的基础无关。

如果你有:

byte[] x = { 127 };
System.out.println(x[0]);

将打印 127,因为它在 byte 的范围内。如果你有:

byte[] x = { (byte) 128 };
System.out.println(x[0]);

... 将打印 -128。如果您没有显式转换,那将是非常出乎意料的。

诚然,有关“精度”的错误消息很奇怪 - 而不是我收到的消息。我看到这个:

error: incompatible types: possible lossy conversion from int to byte

有损转换,所以没关系。不过,我不会谈论这是一个 precision 问题,这是我期望将(比如)double 转换为 float

就JLS而言,相关部分是5.2,它适用于ArrayInitializer中的每个VariableInitializer。

这是重要的部分(强调我的):

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

您提供的示例无法在 byte 类型中表示,因此出现错误。