如何将int转换为byte []并重新设置byte []的值

问题描述:

我认为int和byte []之间的转换非常简单,我尝试将一个值转换为byte [],然后重新设置值在其他函数中获取int。如int x = 89;和byte [] y;铸造y =(byte [])x,不起作用。 我该怎么做?我有什么需要,例如:如何将int转换为byte []并重新设置byte []的值

     in func1       in func2 
int x ;   x value is casted in the y  y is taken and x value is 
byte[] y;            extracted 

     ------func1----------- --------func2--------- 
    ^    ^^     ^
x = 33 ==feed into==> byte [] ===> extraction ===> 33 

你不能在Java中使用类型转换来做这种事情。这些是转换,并且必须以编程方式完成。

例如:

int input = ... 
    byte[] output = new byte[4]; 
    output[0] = (byte) ((input >> 24) & 0xff); 
    output[1] = (byte) ((input >> 16) & 0xff); 
    output[2] = (byte) ((input >> 8) & 0xff); 
    output[3] = (byte) (input & 0xff); 

(这样做有特殊的转换更优雅的方式)

byte[]去“别的东西”同样是一个转换......这可能会或可能不可能,取决于“别的东西”是什么。

对于转换回一个int:

byte[] input = ... 
    int output = (input[0] << 24) | (input[1] << 16) | (input[2] << 8) | input[3] 

这个问答& A给出了其他的方法来做到这一点的int < - >byte[]Java integer to byte array

+0

其他东西是int为我的情况。可能吗 – user2349809 2013-05-05 10:58:05

使用ByteBuffer

ByteBuffer b = ByteBuffer.allocate(4); 
b.putInt(0xABABABAB); 
byte[] arr = b.array(); 

BigInteger类。

byte[] arr = BigInteger.valueOf(0xABABABAB).toByteArray(); 
+0

但我的号码不是形式的0xABABABAB。 – user2349809 2013-05-05 10:55:46