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

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


例如


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


// CONVERSION OPERATION

// return the numeric value

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


蝴蝶不菲
浏览 949回答 3
3回答

慕哥6287543

假设第一个字节是最低有效字节:long value = 0;for (int i = 0; i < by.length; i++){&nbsp; &nbsp;value += ((long) by[i] & 0xffL) << (8 * i);}第一个字节是最高位,然后略有不同:long value = 0;for (int i = 0; i < by.length; i++){&nbsp; &nbsp;value = (value << 8) + (by[i] & 0xff);}如果您有8个以上的字节,请用BigInteger替换long 。感谢Aaron Digulla纠正了我的错误。

慕慕森

可以使用Buffer作为java.nio软件包一部分提供的来执行转换。在此,源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通过查看具有多个值的数组可以带来s 的魅力。例如,如果我们有一个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);结果:14

HUH函数

如果这是一个8字节的数值,则可以尝试:BigInteger n = new BigInteger(byteArray);如果这是UTF-8字符缓冲区,则可以尝试:BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));
打开App,查看更多内容
随时随地看视频慕课网APP