java整数到字节,以及字节到整数

我知道 – 在Java-int中是4个字节。 但我希望将int转换为n字节数组,其中n可以是1,2,3或4个字节。 我想把它作为有符号的字节/字节,所以如果我需要将它们转换回int(事件,如果它是1字节),我得到相同的signed int。 我完全清楚从int转换为3或更低字节时精度损失的可能性。

我设法从int转换为n字节,但将其转换回负数会产生无符号结果。

编辑:

int到bytes(参数n指定所需的字节数1,2,3或4,无论可能的进动丢失)

public static byte[] intToBytes(int x, int n) { byte[] bytes = new byte[n]; for (int i = 0; i >>= 8) bytes[i] = (byte) (x & 0xFF); return bytes; } 

bytes到int(不管1,2,3或4的字节数)

 public static int bytesToInt(byte[] x) { int value = 0; for(int i = 0; i < x.length; i++) value += ((long) x[i] & 0xffL) << (8 * i); return value; } 

int转换器的字节可能存在问题。

BigInteger.toByteArray()会为你做这个……

返回一个包含此BigInteger的二进制补码表示的字节数组。 字节数组将采用big-endian字节顺序:最重要的字节位于第0个元素中。 该数组将包含表示此BigInteger,所需的最小字节数BigInteger,包括至少一个符号位,即(ceil((this.bitLength() + 1)/8)) 。 (此表示与(byte[])构造函数兼容。)

示例代码:

 final BigInteger bi = BigInteger.valueOf(256); final byte[] bytes = bi.toByteArray(); System.out.println(Arrays.toString(bytes)); 

打印:

 [1, 0] 

要从字节数组返回到int,请使用BigInteger(byte[])构造函数:

 final int i = new BigInteger(bytes).intValue(); System.out.println(i); 

打印预期的:

 256 

无论如何,这是我扔的代码:

 public static void main(String[] args) throws Exception { final byte[] bi = encode(-1); System.out.println(Arrays.toString(bi)); System.out.println(decode(bi)); } private static int decode(byte[] bi) { return bi[3] & 0xFF | (bi[2] & 0xFF) << 8 | (bi[1] & 0xFF) << 16 | (bi[0] & 0xFF) << 24; } private static byte[] encode(int i) { return new byte[] { (byte) (i >>> 24), (byte) ((i << 8) >>> 24), (byte) ((i << 16) >>> 24), (byte) ((i << 24) >>> 24) }; } 

就像是:

 int unsignedByte = ((int)bytes[i]) & 0xFF; int n = 0; n |= unsignedByte << 24;