可变长度到数字的字节数组

byte array with variable length to number

我需要将数字转换为字节数组,然后再转换回数字。 问题是字节数​​组的大小可变,所以我需要根据字节长度转换一个数字,我想出的方法是:(Java)

private static byte[] toArray(long value, int bytes) {
    byte[] res = new byte[bytes];

    final int max = bytes*8;
    for(int i = 1; i <= bytes; i++)
        res[i - 1] = (byte) (value >> (max - 8 * i));

    return res;
}

private static long toLong(byte[] value) {
    long res = 0;

    for (byte b : value)
        res = (res << 8) | (b & 0xff);

    return res;
}

这里我使用了long,因为8是我们可以使用的最大字节数。 这种方法对正数非常有效,但我似乎无法对负数进行解码。

编辑:为了对此进行测试,我尝试处理值 Integer.MIN_VALUE + 1 (-2147483647) 和 4 个字节

看看 Apache Common Conversion.intToByteArray util 方法。

Java文档:

Converts a int into an array of byte using the default (little endian, Lsb0) byte and bit ordering

After accepting this as working solution, the Asker made some further optimizations.
I have included their own
linked code below for reference :

private static long toLong(byte[] value) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    final byte val = (byte) (value[0] < 0 ? 0xFF : 0);

    for(int i = value.length; i < Long.BYTES; i++)
        buffer.put(val);

    buffer.put(value);
    return buffer.getLong(0);
}

旧答案

编辑:基于评论(更好地理解问题)

要让您的 toLong 函数同时处理 negativepositive 数字,试试这个:

private static long toLong(byte[] value) 
{
    long res = 0;
    int tempInt = 0;
    String tempStr = ""; //holds temp string Hex values

    tempStr = bytesToHex(value);

    if (value[0] < 0 ) 
    { 
        tempInt = value.length;
        for (int i=tempInt; i<8; i++) { tempStr = ("FF" + tempStr); }

        res = Long.parseUnsignedLong(tempStr, 16); 
    }
    else { res = Long.parseLong(tempStr, 16); }

    return res;

}

下面是相关的 bytesToHex 函数(re-factored 与任何 byte[] 输入一起工作 out-of-box...)

public static String bytesToHex(byte[] bytes)
{ String tempStr = ""; tempStr = DatatypeConverter.printHexBinary(bytes); return tempStr; }