2016-04-01 126 views
4

我有這個小碼:BigInteger如何在Java中將字節數組轉換爲數字?

public static void main(String[] args) { 

    byte[] bytesArray = {7,34}; 
    BigInteger bytesTointeger= new BigInteger(bytesArray); 
    System.out.println(bytesTointeger); 

} 

輸出:1826

我的問題是,到底發生了什麼字節數組{7,34}如何轉換成這一數字1826年,那是什麼導致了操作這個結果?像如何手動轉換它

回答

11

數字1826是二進制,11100100010。 如果拆分,在8位組,你會得到如下:

00000111 00100010

即數字7和34

+0

謝謝!這是有幫助的 – Zizoo

0

7和34轉換成二進制,給00000111和00100010.After加入它變成11100100010這是在十進制1826.

0

如上所述,這將創建一個BigDecimal從它的字節表示big-endian order

如果我們使用long存儲結果,手動轉換可能看起來像下面這樣:

long bytesToLong(byte[] bs) { 
    long res = 0; 
    for (byte b : bs) { 
     res <<= 8; // make room for next byte 
     res |= b; // append next byte 
    } 
    return res; 
} 

E.摹:

byte[] bs;  
bs = new byte[]{ 7, 34 }; 
assertEquals(new BigInteger(bs).longValue(), bytesToLong(bs)); // 1826 
bs = new byte[]{ -1 }; 
assertEquals(new BigInteger(bs).longValue(), bytesToLong(bs)); // -1 
相關問題