Java char
是一种 16 位数据类型,但是在对其执行算术时它是有符号还是无符号?
你能将它用作算术中的无符号 16 位整数吗?
例如,以下内容正确吗?
char c1;
char c2;
int i = c1 << 16 | c2;
或者是否有必要先去除 c2 上的符号扩展位?
(我确信这个问题的答案在其他地方,但显然搜索似乎没有找到)。
最佳答案
char
是无符号的。来自 JLS§4.2.1 :
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
...但请注意,当您使用 various mathematic operations 中的任何一个时在它们上(包括按位运算和移位运算),它们根据另一个操作数的类型扩展为另一种类型,并且该其他类型很可能被签名:
Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type
double
, the other is converted todouble
.Otherwise, if either operand is of type
float
, the other is converted tofloat
.Otherwise, if either operand is of type
long
, the other is converted tolong
.Otherwise, both operands are converted to type
int
.
例如,char + char
是 int
,因此:
public class Example {
public static void main(String[] args) {
char a = 1;
char b = 2;
char c = a + b; // error: incompatible types: possible lossy conversion from int to char
System.out.println(c);
}
}
关于位扩展,如果我们遵循 the link above扩大原始转换:
A widening conversion of a
char
to an integral type T zero-extends the representation of the char value to fill the wider format.
因此,char
0xFFFF 变为 int
0x0000FFFF,而不是 0xFFFFFFFF。
关于java - Java char 对于算术来说是有符号的还是无符号的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54924058/