日期:2014-05-20  浏览次数:20690 次

关于byte to char 不属于widening primitive conversion
JLS中一共定义了19种Widening Primitive Conversion

? byte to short, int, long, float, or double
? short to int, long, float, or double
? char to int, long, float, or double
? int to long, float, or double
? long to float or double
? float to double

可以发现没有byte to char,对此,Java Puzzlers中是这样解释的:
it is impossible to represent a negative byte value as a char. Therefore, the conversion from byte to char is not considered a widening primitive conversion [JLS 5.1.2], but a widening and narrowing primitive conversion [JLS 5.1.4]: The byte is converted to an int and the int to a char.

这是为什么?我对他的解释感到疑惑,negative byte自然是不能表示为char,但是符号扩展至16位后的negative byte还不能表示为一个char?即使是 1111 1111 1111 1111 它不照样可以表示为一个char嘛?






------解决方案--------------------
JLS 5.1.2 中的段落:
A widening primitive conversion does not lose information about the overall magnitude of a numeric value.

这是对 widening primitive conversion 的设计要求。
而把一个负数 byte 变换成 char 时,因为 char 只覆盖了部分正数,是无法满足这一要求的。
比如把 byte b=-1 变换成 char, 自然的它的值为 0xFFFF, 也就是65535。结果 numeric value 变了,它无法满足上面的要求。
(你可以试图,把 (byte)(-1) 变换成其他的 char 值,但结果必然是一个正数,从而改变了它的 numeric value)

另一边,narrowing primitive conversion 不要求这些。

A narrowing primitive conversion may lose information about the overall magnitude of a numeric value and may also lose precision and range.

所以 char 到 byte 可以是 narrowing primitive conversion。

最后,关于你的例子:



------解决方案--------------------
在5.1.4 Widening and Narrowing Primitive Conversions中涉及到了byte to char
解释:First, the byte is converted to an int via widening primitive conversion, and then the resulting int is converted to a char by narrowing primitive conversion.

字面解释下先通过widening primitive conversion把byte转换为int,然后再通过narrowing primitive conversion把int转换为char。

也就是(byte to int) to char。

俺感觉这应该是跟这个类型的内存分配和01存储有关系吧。