为什么将short转换为char是一个狭窄的转换?

为什么将short转换为char是一个狭窄的转换?,第1张

为什么将short转换为char是一个狭窄的转换?

这是因为a

short
可以保持负值,而
char
您可能从中看不到
Character.MIN_VALUE
。让我举几个例子。

  short s = -124;  char c = 124; // OK, no compile time error  char d = -124; // NOT OK, compile time error since char cannot hold -ve values  char e = s; // NOT OK, compile time error since a short might have -ve values which char won't be able to hold  char f = (char)s; // OK, type casting. The negative number -124 gets converted to 65412 so that char can hold it  System.out.println((short)f); // -124, gets converted back to a number short can hold because short won't be able to hold 65412  System.out.println((int)f); // 65412, gets converted to 65412 because int can easily hold it.

A(负)号

-n
转换为时
char
,变得
2^16-n
。因此,
-124
成为
2^16-124 = 65412

我希望这有帮助。



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5429421.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存