gpt4 book ai didi

java - 为什么对字节进行右移 (>>) 位运算会产生奇怪的结果?

转载 作者:行者123 更新时间:2023-12-04 00:33:52 26 4
gpt4 key购买 nike

有一个字节[01100111],我必须以这种方式打破它[0|11|00111]所以在将这个字节的部分移动到不同的字节后,我会得到:

[00000000] => 0 (in decimal)
[00000011] => 3 (in decimal)
[00000111] => 7 (in decimal)

我尝试用这样的代码来做到这一点:

byte b=(byte)0x67;
byte b1=(byte)(first>>7);
byte b2=(byte)((byte)(first<<1)>>6);
byte b3=(byte)((byte)(first<<3)>>3);

但是我得到了:

b1 is 0
b2 is -1 //but I need 3....
b3 is 7

我哪里错了?

谢谢

最佳答案

您的结果正在自动 sign-extended .

尝试掩蔽和移位而不是双移位,即:

byte b1=(byte)(first>>7) & 0x01;
byte b2=(byte)(first>>5) & 0x03;
byte b3=(byte)(first>>0) & 0x1F;

关于java - 为什么对字节进行右移 (>>) 位运算会产生奇怪的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5623738/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com