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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6374915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:26:21  来源:igfitidea点击:

Java - Convert int to Byte Array of 4 Bytes?

javabytebuffer

提问by Petey B

Possible Duplicate:
Convert integer into byte array (Java)

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

I need to store the length of a buffer, in a byte array 4 bytes large.

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

Pseudo code:

伪代码:

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

What would be the best way of accomplishing this? Keeping in mind I must convert that byte array back to an integer later.

实现这一目标的最佳方法是什么?请记住,我必须稍后将该字节数组转换回整数。

采纳答案by Waldheinz

You can convert yourIntto bytes by using a ByteBufferlike this:

您可以yourInt使用ByteBuffer这样的方式转换为字节:

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

Beware that you might have to think about the byte orderwhen doing so.

请注意,这样做时您可能必须考虑字节顺序

回答by Sorrow

This should work:

这应该有效:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

Code taken from here.

代码取自此处

EditAn even simpler solution is given in this thread.

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

回答by Stas Jaro

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

回答by Hari Perev

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