簡體   English   中英

Java字節操作-將3字節轉換為整數數據

[英]Java Byte Operation - Converting 3 Byte To Integer Data

我有一些字節整數操作。 但我不知道問題所在。

首先,我有一個十六進制數據,我將其保存為整數

public static final int hexData = 0xDFC10A;

我正在使用此功能將其轉換為字節數組:

public static byte[] hexToByteArray(int hexNum)
    {
        ArrayList<Byte> byteBuffer = new ArrayList<>();

        while (true)
        {
            byteBuffer.add(0, (byte) (hexNum % 256));
            hexNum = hexNum / 256;
            if (hexNum == 0) break;
        }

        byte[] data = new byte[byteBuffer.size()];
        for (int i=0;i<byteBuffer.size();i++){
            data[i] = byteBuffer.get(i).byteValue();
        }


        return data;
    }

我想再次將3字節數組轉換回整數,我該怎么做? 或者,您也可以建議其他轉換功能,例如十六進制至3字節數組和3字節至int謝謝。

UPDATE

在C#中,有人使用以下功能,但無法在Java中工作

 public static int byte3ToInt(byte[] byte3){
        int res = 0;
        for (int i = 0; i < 3; i++)
        {
            res += res * 0xFF + byte3[i];
            if (byte3[i] < 0x7F)
            {
                break;
            }
        }
        return res;
    }

這將為您帶來價值:

(byte3[0] & 0xff) << 16 | (byte3[1] & 0xff) << 8 | (byte3[2] & 0xff)

假設字節數組的長度為3個字節。 如果您還需要轉換較短的數組,則可以使用循環。

可以使用如下邏輯操作編寫另一個方向(int到字節)的轉換:

byte3[0] = (byte)(hexData >> 16);
byte3[1] = (byte)(hexData >> 8);
byte3[2] = (byte)(hexData);

您可以使用Java NIO的ByteBuffer:

byte[] bytes = ByteBuffer.allocate(4).putInt(hexNum).array();

反之亦然。 看看這個

舉個例子:

final byte[] array = new byte[] { 0x00, (byte) 0xdf, (byte) 0xc1, 0x0a };//you need 4 bytes to get an integer (padding with a 0 byte)
final int x = ByteBuffer.wrap(array).getInt();
// x contains the int 0x00dfc10a

如果要執行類似於C#代碼的操作:

public static int byte3ToInt(final byte[] byte3) {
        int res = 0;
        for (int i = 0; i < 3; i++)
        {
        res *= 256;
        if (byte3[i] < 0)
        {
            res += 256 + byte3[i]; //signed to unsigned conversion
        } else
        {
            res += byte3[i];
        }
        }
        return res;
    }

將Integer轉換為十六進制: integer.toHexString()

將hexString轉換為Integer: Integer.parseInt("FF", 16);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM