简体   繁体   English

如何将字节数组转换为 int/long

[英]How to convert byte array to int/long

I have these byte arrays:我有这些字节 arrays:字节数组

I have to order to little endian before to convert.在转换之前我必须订购小端。

In first case, I do the conversion easyly:在第一种情况下,我很容易进行转换:

byte[] serial = {-91, -101, 62, 55};
int serialNumber = java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt();
//serialNumber == 926849957 //Nice, works!!!!

In second case, the conversion doesn't works:在第二种情况下,转换不起作用:

byte[] serial = {-45, 12, 115, -28};
int serialNumber = java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt();
//serialNumber == -462222125 //Wrong conversion. The right answer is 3832745171.

The number 3832745171 is larger than Integer.MAX_VALUE , but if I try to convert to long I got a problem too.数字 3832745171 大于Integer.MAX_VALUE ,但如果我尝试转换为 long,我也会遇到问题。

How can I do this?我怎样才能做到这一点? Thanks.谢谢。

Try to convert byte arrays to int/long types.尝试将字节 arrays 转换为 int/long 类型。

byte[] serial = {-45, 12, 115, -28};
int serialNumber = java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt();

This gives you the only representable equivalent of that in a Java int .这为您提供了 Java int中唯一可表示的等价物。

If you want it as an unsigned value, it will only be able to fit in a long , but you can write如果你想把它作为一个无符号值,它只能放在一个long中,但你可以写

Integer.toUnsignedLong(serialNumber)

(That said, you can just store it in an int. It's still the same value, it just does math differently and prints differently; you can convert it only when necessary.) (也就是说,您可以将它存储在一个 int 中。它仍然是相同的值,只是计算方式不同,打印方式不同;您可以仅在必要时转换它。)

3832745171 is the value if you could use unsigned integer, but it's not a valid value of a signed integer. It differs from -462222125 by Math.pow(2,32) 3832745171 是您可以使用无符号 integer 时的值,但它不是有符号 integer 的有效值。它与 -462222125 的区别在于Math.pow(2,32)

From the example in http://www.java2s.com/example/java/java.nio/get-unsigned-int-from-bytebuffer.html it seems possible to use a value in "long" to store the "Unsigned Integer" value.http://www.java2s.com/example/java/java.nio/get-unsigned-int-from-bytebuffer.html中的示例来看,似乎可以使用“long”中的值来存储“Unsigned Integer” “ 价值。

Combining the logic in the link with your code, it would be like long serialNumber = ( java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL)将链接中的逻辑与您的代码结合起来,就像long serialNumber = ( java.nio.ByteBuffer.wrap(serial).order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL)

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

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