java整数到字节,以及字节到整数 [英] java integer to byte, and byte to integer

查看:315
本文介绍了java整数到字节,以及字节到整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am aware -that in Java- int is 4 bytes. But I wish to covert an int to n-bytes array, where n can be 1, 2, 3, or 4 bytes. I want to have it as signed byte/bytes, so that if I need to convert them back to int (event if it was 1 byte), I get the same signed int. I am fully aware about the possibility of precision loss when converting from int to 3 or lower bytes.

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

I managed to convert from int to n-byte, but converting it back for a negative number yield unsigned results.

编辑:

int to bytes (参数n指定所需的字节数1,2,3或4,不管可能的进动损失)

int to bytes (parameter n specify the number of bytes required 1,2,3, or 4 regardless of possible precession loss)

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

字节到int(无论字节数1,2,3,或者4)

bytes to int (regardless of how many bytes 1,2,3, or 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;
}

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

There is probably a problem in the bytes to int converter.

推荐答案

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

BigInteger.toByteArray() will do this for you ...


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

Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)). (This representation is compatible with the (byte[]) constructor.)

示例代码:

final BigInteger bi = BigInteger.valueOf(256);
final byte[] bytes = bi.toByteArray();

System.out.println(Arrays.toString(bytes));

打印:

[1, 0]

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

To go from the byte array back to a int, use the BigInteger(byte[]) constructor:

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

打印预期:

256

这篇关于java整数到字节,以及字节到整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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