转换成整数,字节数组(JAVA) [英] Convert integer into byte array (Java)

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

问题描述

因为Java没有提供缺省的方式来做到这一点,

since Java doesn't provide a default way to do this,

什么是一个整数转换成字节数组的快捷方式?

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

例如。 0xAABBCCDD => {AA,BB,CC,DD}

e.g. 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();

设置字节顺序确保结果[0] ==和0xAA 结果[1] ==为0xBB 结果[2] ==的0xCC 结果[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天全站免登陆