java - Java char 对于算术来说是有符号的还是无符号的?

标签 java char unsigned

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 中的任何一个时在它们上(包括按位运算和移位运算),它们根据另一个操作数的类型扩展为另一种类型,并且该其他类型很可能被签名:

  1. 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 to double.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to type int.

例如,char + charint,因此:

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/

相关文章:

java - 如何使用流编写模式方法

java - 在Java中,两个字符相加的结果是int还是char?

c++ - 如果一个整数默认是有符号的,那么为什么会存在signed关键字呢?

在 C 中复制无符号 int 数组

java - 如何使用 Java 使用 Selenium WebDriver 验证按钮是否被单击

java - 在事务上下文中使用 findBy

Java 1.4.2 的 replace() 只接受字符,我怎样才能得到 char 值\n 和\r\n 回车?

c - 计算所选单词的字符数的程序

c++ - 为什么将有符号值分配给无符号整数时编译器不给出错误? - C++

java - 在eclipse中打开浏览器哪种方式更好?