Java - 将int转换为4字节的字节数组?

84

可能是重复问题:
将整数转换为字节数组(Java)

我需要将一个缓冲区的长度存储在一个4字节大的字节数组中。

伪代码:

private byte[] convertLengthToByte(byte[] myBuffer)
{
    int length = myBuffer.length;

    byte[] byteLength = new byte[4];

    //here is where I need to convert the int length to a byte array
    byteLength = length.toByteArray;

    return byteLength;
}

如何最好地实现这个功能?要记住我后来必须将该字节数组转换回整数。


看一下这个:https://dev59.com/XW035IYBdhLWcg3weP7f - TacB0sS
4个回答

145

您可以通过使用ByteBufferyourInt转换为字节,如下所示:

return ByteBuffer.allocate(4).putInt(yourInt).array();

请注意,在这样做时您可能需要考虑字节顺序


1
这是更好的方式(获取平台的ByteOrder):ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array(); - helmy
2
如果哪个更好取决于您想要用它做什么。它可能会快一点,但当您希望将这些字节发送到网络甚至写入文件时,字节顺序依赖于平台是不可取的。 - Waldheinz

50
public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

24
这个应该可以工作:
public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

代码摘自这里

编辑这个线程中给出了一个更简单的解决方案。


1
你应该意识到顺序的问题。在这种情况下,顺序是大端序,从最高位到最低位。 - Error

22
int integer = 60;
byte[] bytes = new byte[4];
for (int i = 0; i < 4; i++) {
    bytes[i] = (byte)(integer >>> (i * 8));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接