将整数转换为字节数组(Java) [英] Convert integer into byte array (Java)

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

问题描述

Integer 转换为 Byte Array 的快速方法是什么?

what's a fast way to convert an Integer into a Byte Array?

例如<代码>0xAABBCCDD =>{AA、BB、CC、DD}

推荐答案

查看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] == 0xCCresult[3] == 0xDD.

Setting the byte order ensures that result[0] == 0xAA, result[1] == 0xBB, result[2] == 0xCC and result[3] == 0xDD.

或者,您也可以手动完成:

Or alternatively, you could do it manually:

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() 使用的辅助方法:

The ByteBuffer class was designed for such dirty hands tasks though. In fact the private java.nio.Bits defines these helper methods that are used by 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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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