我得到一个整数:1695609641

当我使用方法:

String hex = Integer.toHexString(1695609641);
system.out.println(hex); 

给:

6510f329

但是我想要一个字节数组:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};

我怎么做这个?


当前回答

如何:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

这个主意不是我的。我是从dzone.com上的一些帖子上截取的。

其他回答

下面的块至少可以在UDP上发送int。

Int到字节数组:

public byte[] intToBytes(int my_int) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = new ObjectOutputStream(bos);
    out.writeInt(my_int);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

字节数组到int:

public int bytesToInt(byte[] int_bytes) throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(int_bytes);
    ObjectInputStream ois = new ObjectInputStream(bis);
    int my_int = ois.readInt();
    ois.close();
    return my_int;
}

使用番石榴:

byte[] bytearray = Ints.toByteArray(1695609641);

org.apache.hadoop.hbase.util.Bytes类有很多方便的byte[]转换方法,但是你可能不想仅仅为了这个目的就把整个HBase jar添加到你的项目中。令人惊讶的是,这种方法不仅在JDK中缺少AFAIK,而且在明显的库中也缺少AFAIK,比如commons io。

BigInteger.valueOf(1695609641).toByteArray()

byte[] IntToByteArray( int data ) {    
    byte[] result = new byte[4];
    result[0] = (byte) ((data & 0xFF000000) >> 24);
    result[1] = (byte) ((data & 0x00FF0000) >> 16);
    result[2] = (byte) ((data & 0x0000FF00) >> 8);
    result[3] = (byte) ((data & 0x000000FF) >> 0);
    return result;        
}