我需要將數字轉換爲字節數組,然後返回數字。 問題是字節數組的大小是可變的,所以我需要將數字轉換給他的字節長度,我想出了一個方法爲:(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個字節試圖
不知道如果你的問題現在已經解決了,但...看看我的答案是否可以幫助你處理l arge負值。 –