Java - 将int转换为4字节的字节数组? [英] Java - Convert int to Byte Array of 4 Bytes?

查看:295
本文介绍了Java - 将int转换为4字节的字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将整数转换为字节数组(Java)

我需要以4字节大的字节数组存储缓冲区的长度。

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

伪代码:

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.

推荐答案

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

You can convert yourInt to bytes by using a ByteBuffer like this:

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

请注意,您可能需要考虑字节顺序

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

这篇关于Java - 将int转换为4字节的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆