- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
谁能告诉我为什么这种显式转换会产生不同的结果,即使 short/char 的大小都是 16 位?
package jh;
public class Main {
public static void main(String[] args) {
byte b = (byte)255;
System.out.println("Size of short: " + Short.SIZE);
System.out.println("Size of char: " + Character.SIZE);
System.out.println((int)((short)b));
System.out.println((int)((char)b));
}
}
输出:
Size of short: 16
Size of char: 16
-1
65535
最佳答案
byte: 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.
short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
因此,简而言之(请原谅双关语),按位它们是相同的。但是对于与 short
相同的位模式,char
表示不同的数字值。
这还伴随着符号扩展功能:(byte) 255
将表示一个字节值,所有位都已设置 (0b11111111
),即 - 1、在twos complement . Java在向上转换的时候做了一个符号扩展操作,所以如果符号位为0,那么高位也都为0,而当符号位为1时,高位也都为1。现在这意味着 -1 在所有带符号的整数数据类型中都意味着 -1(0b1111111111111111
在此示例中表示 short
)。但不是 char - 当设置了所有位时,它等于正最大值 - 65535。
关于Java - 显式转换为 char/short,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18870254/
我是一名优秀的程序员,十分优秀!