gpt4 book ai didi

java - 如何将字节数组转换为其数值(Java)?

转载 作者:IT老高 更新时间:2023-10-28 11:38:48 25 4
gpt4 key购买 nike

我有一个 8 字节数组,我想将其转换为对应的数值。

例如

byte[] by = new byte[8];  // the byte array is stored in 'by'

// CONVERSION OPERATION
// return the numeric value

我想要一个可以执行上述转换操作的方法。

最佳答案

可以使用 Buffer作为 java.nio 的一部分提供的 s包来执行转换。

这里,源 byte[] 数组的长度为 8,这是与 long 值对应的大小。

首先,byte[] 数组被包裹在 ByteBuffer 中。 ,然后是 ByteBuffer.getLong调用方法获取long值:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

结果

4

感谢 dfa 在评论中指出 ByteBuffer.getLong 方法。


虽然它可能不适用于这种情况,但 Buffer 的美妙之处在于查看具有多个值的数组。

例如,如果我们有一个 8 字节数组,并且我们想将其视为两个 int 值,我们可以将 byte[] 数组包装在 ByteBuffer,被视为 IntBuffer并通过 IntBuffer.get 获取值:

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);

System.out.println(i0);
System.out.println(i1);

结果:

1
4

关于java - 如何将字节数组转换为其数值(Java)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1026761/

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