Java整数到字节数组Blackberry J2ME

时间:2012-03-06 16:17:58

标签: java java-me type-conversion blackberry-jde

我找到了this解决方案,但它似乎适用于Java SE。我找不到System.out.format()函数的替代方法。另外,我已将ByteBuffer.allocate()功能更改为ByteBuffer.allocateDirect()这是正确的吗?

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

    for (byte b : bytes) {
         System.out.format("0x%x ", b);
    }

谢谢。

2 个答案:

答案 0 :(得分:2)

如果你想在整个Java的序列化和远程处理库中使用network byte order aka big-endian命令:

static byte[] intToBytesBigEndian(int i) {
  return new byte[] {
    (byte) ((i >>> 24) & 0xff),
    (byte) ((i >>> 16) & 0xff),
    (byte) ((i >>> 8) & 0xff),
    (byte) (i & 0xff),
  };
}

答案 1 :(得分:0)

// 32-bit integer = 4 bytes (8 bits each)
int i = 1695609641;
byte[] bytes = new byte[4];

// big-endian, store most significant byte in byte 0
byte[3] = (byte)(i & 0xff);
i >>= 8;
byte[2] = (byte)(i & 0xff);
i >>= 8;
byte[1] = (byte)(i & 0xff);
i >>= 8;
byte[0] = (byte)(i & 0xff);