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] == 0xAA,result [1] == 0xBB,result [2] == 0xCC和result [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); }


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部