我正在尝试将十六进制转换为Big Integer.基本上我有32个字符= 16个字节,所以我希望BigInteger也有16个字节,但是在某些情况下,即hex以99开头.它生成的其他字节为0.我正在使用
new BigInteger(hex, 16)
如何避免第17个字节?
解决方法:
Immutable arbitrary-precision integers. All operations behave as if
BigIntegers were represented in two’s-complement notation (like Java’s
primitive integer types).
Translates the String representation of a BigInteger in the specified
radix into a BigInteger. The String representation consists of an
optional minus or plus sign followed by a sequence of one or more
digits in the specified radix. The character-to-digit mapping is
provided by Character.digit. The String may not contain any extraneous
characters (whitespace, for example).
这意味着,如果使用新的BigInteger(“ 99000000000000000000000000000000000000”,16)进行调用,则将获得一个BigInteger,该值将保持该值(为正值),就像用二进制补码表示的那样.二进制补码中的那个正值不能容纳16个字节,因此最终结果当然是17个字节长.
如果您使用介于之间的值(包括两者)进行调用,则可以确保获得一个最大为16个字节的BigInteger:
- new BigInteger( "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", 16)
- new BigInteger("-80000000000000000000000000000000", 16)
任何高于第一个值或小于最后一个值的值都将导致超过16个字节.
标签:java
来源: https://codeday.me/bug/20191119/2039002.html