您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Java将整数转换为字节数组

Java将整数转换为字节数组

看看ByteBuffer类。

ByteBuffer b = ByteBuffer.allocate(4);
//b.order(ByteOrder.BIG_ENDIAN); // optional, the initial order of a byte buffer is always BIG_ENDIAN.
b.putInt(0xAABBCCDD);

byte[] result = b.array();

设置字节顺序保证了result[0] == 0xAAresult[1] == 0xBBresult[2] == 0xCCresult[3] == 0xDD

或者,你可以手动执行以下操作:

byte[] toBytes(int i)
{
  byte[] result = new byte[4];

  result[0] = (byte) (i >> 24);
  result[1] = (byte) (i >> 16);
  result[2] = (byte) (i >> 8);
  result[3] = (byte) (i /*>> 0*/);

  return result;
}

ByteBuffer班是专为尽管这样的脏手任务。实际上,私有java.nio.Bits定义了以下辅助方法ByteBuffer.putInt()

private static byte int3(int x) { return (byte)(x >> 24); }
private static byte int2(int x) { return (byte)(x >> 16); }
private static byte int1(int x) { return (byte)(x >>  8); }
private static byte int0(int x) { return (byte)(x >>  0); }
java 2022/1/1 18:20:39 有630人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶