String和字节数组中BigInteger值的差异

Har*_*ish 2 java string android bytearray biginteger

有人可以解释下面两个BigInteger初始化之间的区别.

输入:

BigInteger bi1 = new BigInteger("EF", 16);
byte[] ba = new byte[] {(byte)0xEF};
BigInteger bi2 = new BigInteger(ba);
Log.d("BIGINTEGER", "Big Integer1 = " + bi1.toString(16));
Log.d("BIGINTEGER", "Big Integer2 = " + bi2.toString(16));
Run Code Online (Sandbox Code Playgroud)

输出:

Big Integer1 = ef
Big Integer2 = -11
Run Code Online (Sandbox Code Playgroud)

如何从字节数组中使用值"EF"初始化BigInteger?

fai*_*zan 5

来自BigInteger文档

构造函数和描述

BigInteger(byte [] val)

将包含BigInteger的二进制补码二进制表示的字节数组转换为BigInteger.

二元补充是真正的原因.

让我们看看如何......

(Byte)0xef in binary = 11101111现在将其转换回Int,你得到-17(基数10)或-11(基数16).

现在来看看

byte[] ba = new byte[] {0, (byte)0xEF};
Run Code Online (Sandbox Code Playgroud)

这具有(Byte)0xef但前缀为0.这意味着该数组具有00000000 11101111,其在转换时给出正确的结果.

为什么之前的案例有所不同?

查看2的补充规则 - SO答案,强制性维基百科链接

另一种思考方式

十进制中的0xEF = 239

字节范围= -127到128

我们有溢出.

239 - 128 = 111

现在从后面计算这个111(数值数据类型具有这种循环行为,再次由于2的补码表示).

例如: 129.toByte = -127

(129 - 128 = 1,从第1个值开始计算= -127)

从后面算起的快捷方式 if x>128 && x<256 then x.toByte = (x - 128) - 128

这里x = 239,因此x.toByte = -17