将整数转换为四字节数组

时间:2014-03-18 05:31:55

标签: java sockets bytearray

目前我正在进行套接字编程,我必须向固件发送字节数。下面的代码用于将int转换为字节数组。

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

}

任何人都可以通过一些小例子让我理解这种正确的转变是如何运作的。

这是将oposite转换为int。

  public static int byteArrayToInt(byte[] b) {
    return b[0] & 0xFF
            | (b[1] & 0xFF) << 8
            | (b[2] & 0xFF) << 16
            | (b[3] & 0xFF) << 24;
}

左移和右移如何运作。

3 个答案:

答案 0 :(得分:1)

实际上,您只需使用以下声明将int值转换为4 byte array

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

但在实现此功能之前,请先查看ByteBuffer的文档,尤其是order方法。

为了理解左移&amp;右移,请转到StackOverflow回答:Java: right shift on negative number

Shishir

答案 1 :(得分:0)

使用ByteBuffer

public static byte[] intToBytes(final int i)
{
    return ByteBuffer.allocate(4).putInt(i).array();
}

public static int bytesToInt(final byte[] b)
{
    return ByteBuffer.wrap(b).getInt();
}

请注意,默认顺序是big endian。这是JVM,也是网络,字节顺序。

答案 2 :(得分:0)

要了解该代码的事情:

  • intbyte转换会切断int的3个最重要字节。
  • 位移
  • 位掩码
  • 当您对值0xFF进行硬编码时,它实际上是int0x000000FF)。当&为负数时,你用byte个字节来摆脱签名int到 - byte转化时的前导1最重要的一个1)。

假设您的int0x1A2B3C4D

public static byte[] intToFourByteArray(int value) {
    return new byte[]{
        (byte) (value),        // Cuts off top, leaves 0x4D
        (byte) (value >> 8),   // Shift gives 0x001A2B3C, cut-off leaves 0x3C
        (byte) (value >> 16),  // Shift gives 0x00001A2B, cut-off leaves 0x2B
        (byte) (value >> 24)}; // Shift gives 0x0000001A, cut-off leaves 0x1A

}

假设我们反馈字节数组0x4D, 0x3C, 0x2B, 0x1A

public static int byteArrayToInt(byte[] b) {
    return b[0] & 0xFF             // That gives 0x0000004D
            | (b[1] & 0xFF) << 8   // Gives 0x0000003C then shifts to 0x00003C00
            | (b[2] & 0xFF) << 16  // Same idea, giving 0x002B0000
            | (b[3] & 0xFF) << 24; // ...and 0x1A000000
}                                  // Finally, the or-ing of them together gives 0x1A2B3C4D
相关问题