2016-12-26 82 views
1

我需要將數字轉換爲字節數組,然後返回數字。 問題是字節數​​組的大小是可變的,所以我需要將數字轉換給他的字節長度,我想出了一個方法爲:(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; 
} 

這裏我用一個長因爲8是我們可以使用的最大字節數。 這種方法與正數完美結合,但我似乎無法使解碼工作與否定。

編輯:測試這個我已經與處理所述值Integer.MIN_VALUE的+ 1(-2147483647)和4個字節試圖

+0

不知道如果你的問題現在已經解決了,但...看看我的答案是否可以幫助你處理l arge負值。 –

回答

1

接受此作爲工作溶液後,將Asker進一步優化了 。
我已經包括自己下面
linked code爲 參考:

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功能同時處理 & 積極數試試這個:

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功能(重新分解與任何byte[]輸入出的現成工作...)

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


+1

這不是可變的,我不能說「把這個數字放在5個字節中」或者「從這5個字節中得到我的號碼」 – SnowyCoder

+0

你不應該只輸入5個字節。所有語言/操作系統一次讀取1,2,4或8個字節。如果您的電話號碼只需要5個字節,那麼您已經處於實際必須讀取8個字節的狀態。使用[** bit-shifting **](http://stackoverflow.com/a/141873/2057709)將您的40位(5個字節)保留在Array的一側,並用零位填充剩餘的3個字節的時隙。 –

+0

我已經做了類似的事情(請參閱我的問題),但問題是我不知道如何處理負值 – SnowyCoder

1

看一看Apache的普通Conversion.intToByteArray util的方法。

的JavaDoc:

一個INT轉換爲使用默認的字節的陣列(小端,LSB0)字節和位次序

+0

剛剛測試過它: – SnowyCoder

+0

'long v = Integer.MIN_VALUE + 1; byte [] res = new byte [4]; longToByteArray(v,0,res,0,4); long out = byteArrayToLong(res,0,0L,0,4); System.out.println(out);'否定性丟失 – SnowyCoder

+0

@SnowyCoder如果這個答案有效,那麼使用'✓'圖標標記爲解決方案。 –