why can bit mask suppress sign extention

yes, bit mask can suppress sign extension, as it changes the number from negative to the positive, you see:

byte b = -1;
char c = (char)(b & 0xff);

 b is originally a byte, and it's negative, after it bitwise AND with the bit mask 0xff, it then becomes positive and thus will no longer be sign extended.

 

yes, as 0xff is an int primitive type, int fact, it is 0x000000ff, it's not a signed int. that it bitwise AND b would get the result into the int type, and then a narrowing primitive conversion to char.

 

the process:

1. byte b is promoted to int, after bitwise AND, it becomes 0x000000ff

2. after casting to char, it becomes 0x00ff which is 255

 

the operands would be promoted to an int, cause there's a law that all arithmetic operations do this to operands of type short, byte or char. this promotion is a widening primitive conversion, so no information is lost.

 

if it is operated like this without the bit mask:

byte b = -1;
char c = (char)b;

because byte is a signed type, sign extension occurs when converting the byte value –1 to a char . The resulting char value has all 16 bits set, so it is equal to 216 – 1, or 65,535.

 

 

referenced by JavaPuzzler Solution 31 and Puzzle 6 Multicast

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值