我正在将bigints转换为二进制,radix16和radix64编码,并看到神秘的msb零填充.这是一个大问题,我可以通过剥离零填充或者做其他事情来解决这个问题吗?
我的测试代码:
String s;
System.out.printf( "%s length %d\n", s = "123456789A", (new BigInteger( s, 16 )).toByteArray().length );
System.out.printf( "%s length %d\n", s = "F23456789A", (new BigInteger( s, 16 )).toByteArray().length );
Run Code Online (Sandbox Code Playgroud)
产生输出:
123456789A length 5
F23456789A length 6
Run Code Online (Sandbox Code Playgroud)
其中较长的阵列在前面没有填充.检查BigInteger.toByteArray()后,我看到:
public byte[] toByteArray() {
int byteLen = bitLength()/8 + 1;
byte[] byteArray = new byte[byteLen];
Run Code Online (Sandbox Code Playgroud)
现在,我可以找到private int bitLength;,但是我无法找到bitLength()的定义,以确定这个类的确切原因 - 也许连接到符号扩展?
Adr*_*lie -1
感谢乔恩·斯基特的回答。这是我用来转换的一些代码,很可能可以对其进行优化。
import java.math.BigInteger;
import java.util.Arrays;
public class UnsignedBigInteger {
public static byte[] toUnsignedByteArray(BigInteger value) {
byte[] signedValue = value.toByteArray();
if(signedValue[0] != 0x00) {
throw new IllegalArgumentException("value must be a psoitive BigInteger");
}
return Arrays.copyOfRange(signedValue, 1, signedValue.length);
}
public static BigInteger fromUnsignedByteArray(byte[] value) {
byte[] signedValue = new byte[value.length + 1];
System.arraycopy(value, 0, signedValue, 1, value.length);
return new BigInteger(signedValue);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6992 次 |
| 最近记录: |