在Java中將字節數組轉換為整數,反之亦然我想將一些數據存儲到Java中的字節數組中。基本上只是每個數字最多可以占用2個字節的數字。我想知道如何將整數轉換為2字節長字節數組,反之亦然。我發現了很多解決方案谷歌搜索,但大多數都沒有解釋代碼中發生了什么。有很多變化的東西,我真的不明白,所以我很感激一個基本的解釋。
3 回答
慕森王
TA貢獻1777條經驗 獲得超3個贊
使用java.nio命名空間中找到的類,特別是ByteBuffer。它可以為您完成所有工作。
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }
慕仙森
TA貢獻1827條經驗 獲得超8個贊
byte[] toByteArray(int value) {
return ByteBuffer.allocate(4).putInt(value).array();}byte[] toByteArray(int value) {
return new byte[] {
(byte)(value >> 24),
(byte)(value >> 16),
(byte)(value >> 8),
(byte)value };}int fromByteArray(byte[] bytes) {
return ByteBuffer.wrap(bytes).getInt();}// packing an array of 4 bytes to an int, big endian, minimal parentheses// operator precedence: <<, &, | // when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to rightint fromByteArray(byte[] bytes) {
return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);}// packing an array of 4 bytes to an int, big endian, clean codeint fromByteArray(byte[] bytes) {
return ((bytes[0] & 0xFF) << 24) |
((bytes[1] & 0xFF) << 16) |
((bytes[2] & 0xFF) << 8 ) |
((bytes[3] & 0xFF) << 0 );}將有符號字節打包到int中時,需要屏蔽掉每個字節,因為由于算術提升規則(在JLS,轉換和促銷中描述),它被符號擴展為32位(而不是零擴展)。
Joshua Bloch和Neal Gafter在Java Puzzlers(“每個字節中的大喜悅”)中描述了一個有趣的謎題。將字節值與int值進行比較時,將字節符號擴展為int,然后將此值與另一個int進行比較
byte[] bytes = (…)if (bytes[0] == 0xFF) {
// dead code, bytes[0] is in the range [-128,127] and thus never equal to 255}請注意,所有數字類型都使用Java簽名,但char是16位無符號整數類型。
森林海
TA貢獻2011條經驗 獲得超2個贊
您還可以將BigInteger用于可變長度字節。您可以將其轉換為long,int或short,以滿足您的需求。
new BigInteger(bytes).intValue();
或表示極性:
new BigInteger(1, bytes).intValue();
要獲取字節只是:
new BigInteger(bytes).toByteArray()
添加回答
舉報
0/150
提交
取消
