java primitive type的cast

(int)(char)(byte)-1;//结果是65535

(int)(short)(byte)-1;//结果是-1

(int)( ((char)(byte)-1) | 0xffff0000);//-1

 

byte[8bits],short[16bits],int[32bits],long是signed[64bits],而char[16bits]是unsigned。

窄类型转换为宽类型的规则是:

1 如果窄类型是signed,则符号位扩展到高位

2 如果窄类型是unsigned,则0扩展到高位。

综合成一句:

窄类型转换为宽类型,符号位会扩展到高位。

宽类型转换为窄类型,直接除去高位。

 

为了避免一些出乎意料的符号位扩展,可以在代码中明确是否扩展。

 

        byte[] b = new byte[]{(byte) 0xdf};
    	int a2 = b[0];
    	System.out.println(Integer.toHexString(a2));//ffffffdf
    	System.out.println(Integer.toHexString(a2 & 0xff));//df

 


If you are converting from a char value c to a wider type and you don't want sign extension, consider using a bit mask for clarity, even though it isn't required:

int i = c & 0xffff;

 

Alternatively, write a comment describing the behavior of the conversion:

int i = c; // Sign extension is not performed

 

If you are converting from a char value c to a wider integral type and you want sign extension, cast the char to a short, which is the same width as a char but signed. Given the subtlety of this code, you should also write a comment:

int i = (short) c; // Cast causes sign extension

由byte扩展成char,会导致符号位扩展,char不会得出我们想要的效果,因此我们需要人工去掉扩展。原理是利用b和整数0xff做与操作,返回宽类型int,去掉了高位的符号位,最后再缩窄为char类型。

If you are converting from a byte value b to a char and you don't want sign extension, you must use a bit mask to suppress it. This is a common idiom, so no comment is necessary:

char c = (char) (b & 0xff);

 

If you are converting from a byte to a char and you want sign extension, write a comment:

char c = (char) b; // Sign extension is performed

 

The lesson is simple: If you can't tell what a program does by looking at it, it probably doesn't do what you want. Strive for clarity.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值