gpt4 book ai didi

java - 在 Java 中从 short 转换为 byte,反之亦然

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:58:13 24 4
gpt4 key购买 nike

我正在尝试将 short 转换为 2 个字节...然后从这 2 个字节尝试获得相同的 short 值。为此,我编写了这段代码:


short oldshort = 700;

byte 333= (byte) (oldshort);
byte byte2= (byte) ((oldshort >> 8) & 0xff);

short newshort = (short) ((byte2 << 8) + byte1);

System.out.println(oldshort);
System.out.println(newshort);

对于 700(oldshort)的值,newhosrt 是 444。经过一些测试,它看起来像\t这段代码只适用于某些值。就像...如果 oldshort=50,那么它会工作正常..但是如果它是 -200,或者大于 127 的值(我认为)它就不起作用。我猜是有符号字节、二进制补码等有问题...但我不知道如何解决。

有什么想法吗?在 Java 中执行此操作的任何 native 方法?提前致谢!

最佳答案

重组时,需要屏蔽byte1,防止其被符号扩展。

例如

    short oldshort = 700;

byte byte1= (byte) (oldshort);
byte byte2= (byte) ((oldshort >> 8) & 0xff);

short newshort = (short) ((byte2 << 8) + (byte1&0xFF);

System.out.println(oldshort);
System.out.println(newshort);

编辑:java 中对字节和短裤的所有操作实际上都是作为整数完成的。所以当你写+byte1,真正发生的是字节首先被转换为整数(符号扩展)。它仍然具有相同的值,但现在有更多的位。然后,我们可以屏蔽掉底部的 8 位,以从 short 中获得原始的 8 位 - 没有符号。

E.g. short =511 = 0x01FE
// lots of 0x000's because the operations are done on 32-bit int's
byte1 = (0x000001FE & 0x000000FF) = (0x01FE & 0xFF) = 0xFE = (byte)-2
byte2 = 0x1

newShort = (byte2 << 8) + (byte1 & 0xFF)
= (0x1 << 8) + (0xFE & 0xFF)
// since the ops are performed as int's
= (0x00000001 << 8) + (0xFFFFFFFE & 0x000000FF)
// 0xFFFFFFFE = -2
= (0x00000100) + (0x000000FE)
= 0x000001FE
= 511

关于java - 在 Java 中从 short 转换为 byte,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3114935/

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