我有这样的字符串
String text = "f001050000000000003d61c1c1df400200c0000009181600ef014000003f20"
我将其转换为字节以将其作为字节循环
byte[] bytes = new BigInteger(text,16).toByteArray();
for (int i = 0; i < bytes.length; i++)
{
System.out.print(String.format("%02x ", bytes[i]));
}
但是当我打印数组值时,它会在实际字符串的开头添加字节 00
!
它应该以 f0
开头,但它以 00
开头!
当我用1
启动索引时,这个00
消失了。
这个00
从哪里来!?
最佳答案
JavaDoc of BigInteger#toByteArray()状态:
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))
.[...]
由于你有一个正数,第一位的二进制补码为零。
关于java - byte[] 中的数组索引有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14616142/