例如:
byte[] by = new byte[8]; // the byte array is stored in 'by'
// CONVERSION OPERATION
// return the numeric value
我希望有一个方法可以执行上述转换操作。
可以使用作为java.nio
包一部分提供的Buffer
来执行转换。
这里,源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
值,我们可以使用ByteBuffer
包装byte[]
数组,将其视为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
假设第一个字节是最不重要的字节:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value += ((long) by[i] & 0xffL) << (8 * i);
}
如果第一个字节是最高有效位,则有些许不同:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value = (value << 8) + (by[i] & 0xff);
}
如果您需要使用的数字类型超过8个字节,请使用BigInteger 代替 long。
感谢 Aaron Digulla 纠正我的错误。
value += ((long)by[i] & 0xffL) << (8 * i);
。 - Luke你可以使用或参考由谷歌提供的Guava库,该库提供了用于长整型和字节数组之间转换的实用方法。我的客户端代码:
long content = 212000607777l;
byte[] numberByte = Longs.toByteArray(content);
logger.info(Longs.fromByteArray(numberByte));
如果这是一个8字节的数字值,你可以尝试:
BigInteger n = new BigInteger(byteArray);
如果这是一个 UTF-8 字符缓冲区,那么您可以尝试:
BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));
您也可以使用BigInteger来处理可变长度的字节。您可以将其转换为适合您需求的Long、Integer或Short。
new BigInteger(bytes).intValue();
new BigInteger(1, bytes).intValue();
数组中的每个单元格都被视为无符号整数:
private int unsignedIntFromByteArray(byte[] bytes) {
int res = 0;
if (bytes == null)
return res;
for (int i=0;i<bytes.length;i++){
res = res | ((bytes[i] & 0xff) << i*8);
}
return res;
}
您可以尝试使用此答案中的代码:https://dev59.com/dUnSa4cB1Zd3GeqPRtxs#68393576
它将字节解析为任意长度的有符号数字。以下是一些示例:
bytesToSignedNumber(false, 0xF1, 0x01, 0x04)
返回 15794436
(3个字节作为int)
bytesToSignedNumber(false, 0xF1, 0x01, 0x01, 0x04)
返回 -251592444
(4个字节作为int)
bytesToSignedNumber(false, 0xF1, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04)
返回 -1080581331768770303
(8个字节中的9个字节作为long)
public static long byteArrayToLong(byte[] bytes) {
return ((long) (bytes[0]) << 56)
+ (((long) bytes[1] & 0xFF) << 48)
+ ((long) (bytes[2] & 0xFF) << 40)
+ ((long) (bytes[3] & 0xFF) << 32)
+ ((long) (bytes[4] & 0xFF) << 24)
+ ((bytes[5] & 0xFF) << 16)
+ ((bytes[6] & 0xFF) << 8)
+ (bytes[7] & 0xFF);
}
new BigInteger(by).longValue()
- user207421