无符号右移的行为应用于字节变量 [英] Behaviour of unsigned right shift applied to byte variable

查看:272
本文介绍了无符号右移的行为应用于字节变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的java代码片段

Consider the following snip of java code

byte b=(byte) 0xf1;
byte c=(byte)(b>>4);
byte d=(byte) (b>>>4);

输出:

c=0xff
d=0xff

预期输出:

c=0x0f

怎么样?
,b为二进制 1111 0001
无符号右移后 0000 1111 因此 0x0f 但为什么 0xff 如何?

how? as b in binary 1111 0001 after unsigned right shift 0000 1111 hence 0x0f but why is it 0xff how?

推荐答案

问题是所有参数在转换操作发生之前首先被提升为 int

The problem is that all arguments are first promoted to int before the shift operation takes place:

byte b = (byte) 0xf1;

b 已签名,因此其值为-15。

b is signed, so its value is -15.

byte c = (byte) (b >> 4);

b 首先符号扩展到整数 -15 = 0xfffffff1 ,然后右移到 0xffffffff 并截断为 0xff 由强制转换为字节

b is first sign-extended to the integer -15 = 0xfffffff1, then shifted right to 0xffffffff and truncated to 0xff by the cast to byte.

byte d = (byte) (b >>> 4);

b 首先符号扩展到整数 -15 = 0xfffffff1 ,然后右移到 0x0fffffff 并截断为 0xff 由强制转换为字节

b is first sign-extended to the integer -15 = 0xfffffff1, then shifted right to 0x0fffffff and truncated to 0xff by the cast to byte.

你可以做(b& ; 0xff)>>> 4 以获得所需的效果。

You can do (b & 0xff) >>> 4 to get the desired effect.

这篇关于无符号右移的行为应用于字节变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆