java 位类型,符号字节类型和Java中位运算符?

quoting from oracle website "byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)".

here, the first two lines are valid but the last is not

byte b = -128;

byte b1 = 127;

byte b2 = b>>>b1;//illegal

Q1) what is meant exactly by 8-bit signed? 128 in binary format would be 1000 0000 and -128 would need an extra bit for the negative sign, where it would fit if all the 8 bits are occupied.

Q2) for int, there is a unsigned right shift operator, but that seems illegal with bytes, why is it so. can overflow not be prevented in case of bytes. In case of int, it works

Thanks for your help

解决方案

Just what it sounds like: There are 8 bits, holding 2^8 = 256 possible values. It's signed, so the range is frmo -128 through 127 (256 values). The most significant bit has a value of -128.

In Java, binary numeric promotion occurs with operations such as b >>> b1. Both types are promoted to int, and the result is an int. However, you can explicitly cast the result back to byte.

Here's the cast:

byte b2 = (byte) (b >>> b1);

The JLS, Section 5.6.2, talks about binary numeric promotion:

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.

(emphasis mine)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值