简体   繁体   English

Unsigned Shift Operator(>>>)并将int转换为Java中的字节数组

[英]Unsigned Shift Operator(>>>) and convert int to byte arrays in java

I want to convert integer to byte[] in java. 我想在Java中将整数转换为byte []。 And I did some research and found the code 我做了一些研究,发现了代码

    public byte[] integerToBytes (int i) {

          byte[] result = new byte[4];
          result[0] = (byte) (i >>> 24);

          result[1] = (byte) (i >>> 16);

          result[2] = (byte) (i >>> 8);

          result[3] = (byte) (i /*>> 0*/);

          return result;
    }

I'm pretty sure the code is right cause it passes the tests. 我很确定代码正确无误,因为它可以通过测试。 However, I'm a little bit confused. 但是,我有点困惑。

Suppose the integer is 36666666. And binary representation is 10001011110111110100101010.I can understand why it is true for result[0] since after the shift, it becomes 10001011(0x22).However,for result[1],after the shift,it becomes 1000101111011111(0x22F7). 假设整数为36666666。二进制表示为10001011110111110100101010。我可以理解为什么对result [0]成立,因为移位后变成了10001011(0x22)。但是,对于result [1],移位之后变成了1000101111011111(0x22F7)。

But what I really want is just 0xF7. 但是我真正想要的只是0xF7。

Can someone explain this to me or I understand this code in a wrong way? 有人可以给我解释一下吗,还是我以错误的方式理解了此代码?

Cheers 干杯

The reason result[1] and others are just the lowest eight bits is due to the the cast to a byte performed on each assignment. 结果[1]和其他结果仅是最低的八位,是由于对每个分配执行的转换为字节。 Casting an int like 0x22F7 to a byte cuts off the top 3 bytes and leaves the least significant byte to be assigned to the new variable. 将一个像0x22F7这样的整数转换为一个字节会截断前3个字节,并保留要分配给新变量的最低有效字节。 Thus 0x22f7 becomes just 0xf7. 因此0x22f7变为0xf7。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM