gpt4 book ai didi

将字节数组转换为整数的有符号和无符号类型的 Java ByteBuffer 问题

转载 作者:搜寻专家 更新时间:2023-11-01 01:47:09 25 4
gpt4 key购买 nike

我期望这样:

ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == 222

但是以下是正确的:

ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == -570425344

我如何解决 Java 对有符号/无符号类型的许多限制中的另一个问题,或者我是否需要完全自己动手?

最佳答案

代码:

public static void main(String[] args) {
ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 });
System.out.println(bb.order());
System.out.println(bb.getInt() == 222);
bb.rewind();
bb.order(ByteOrder.LITTLE_ENDIAN);
System.out.println(bb.order());
System.out.println(bb.getInt() == -570425344);
}

控制台:

BIG_ENDIAN
true
LITTLE_ENDIAN
true

附录:作为引用,“新创建的字节缓冲区的顺序始终是 BIG_ENDIAN 。”— ByteBuffer#order()

关于将字节数组转换为整数的有符号和无符号类型的 Java ByteBuffer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6366560/

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