3 回答

TA貢獻(xiàn)1831條經(jīng)驗 獲得超10個贊
假設(shè)第一個字節(jié)是最低有效字節(jié):
long value = 0;
for (int i = 0; i < by.length; i++)
{
value += ((long) by[i] & 0xffL) << (8 * i);
}
第一個字節(jié)是最高位,然后略有不同:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value = (value << 8) + (by[i] & 0xff);
}
如果您有8個以上的字節(jié),請用BigInteger替換long 。
感謝Aaron Digulla糾正了我的錯誤。

TA貢獻(xiàn)1856條經(jīng)驗 獲得超17個贊
可以使用Buffer作為java.nio軟件包一部分提供的來執(zhí)行轉(zhuǎn)換。
在此,源byte[]數(shù)組的長度為8,這是與long值相對應(yīng)的大小。
首先,將byte[]數(shù)組包裝在中ByteBuffer,然后ByteBuffer.getLong調(diào)用方法以獲取long值:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();
System.out.println(l);
結(jié)果
4
我要感謝dfa指出了ByteBuffer.getLong注釋中的方法。
盡管在這種情況下可能不適用,但是Buffer通過查看具有多個值的數(shù)組可以帶來s 的魅力。
例如,如果我們有一個8字節(jié)的數(shù)組,并且希望將其視為兩個int值,則可以將該byte[]數(shù)組包裝為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);
結(jié)果:
1
4

TA貢獻(xiàn)1836條經(jīng)驗 獲得超4個贊
如果這是一個8字節(jié)的數(shù)值,則可以嘗試:
BigInteger n = new BigInteger(byteArray);
如果這是UTF-8字符緩沖區(qū),則可以嘗試:
BigInteger n = new BigInteger(new String(byteArray, "UTF-8"));
添加回答
舉報