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 字节数组转换回整数,我该怎么做? 或者您也可以建议其他转换函数,例如 hex-to-3-bytes-array 和 3-bytes-to-int 再次感谢您。

更新

在 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;
    }

将整数转换为十六进制:integer.toHexString()

将十六进制字符串转换为整数:Integer.parseInt("FF", 16);

你可以使用 Java NIO 的 ByteBuffer:

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

反之亦然。看看 this.

举个例子:

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;
    }

这将为您提供价值:

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

假设字节数组的长度为 3 个字节。如果您还需要转换更短的数组,您可以使用循环。

反方向的转换(int到bytes)可以写成这样的逻辑操作:

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