gpt4 book ai didi

Java - 显式转换为 char/short

转载 作者:行者123 更新时间:2023-12-04 14:52:13 25 4
gpt4 key购买 nike

谁能告诉我为什么这种显式转换会产生不同的结果,即使 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

最佳答案

来自 Java datatypes doc

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com