Java:ByteArray到正数和反之的转换
Java: ByteArray to positive number and vice versa conversion
我正在寻找一种方法,如何将任意长度的 byte[] 可逆地转换为 positive 数字(数字中的字符串表示形式)。
BigInteger 提供了一个解决方案:
byte[] originalBytes = ...
String string = new BigInteger(originalBytes).toString();
...
byte[] decodedBytes = new BigInteger(string).toByteArray();
但是,我不确定如何优雅地去除负值(或在何处存储符号)并保持过程可逆。
编辑: 只需替换
String string = new BigInteger(originalBytes).toString();
和
String string = new BigInteger(1, originalBytes).toString();
1,
表示传递的数组代表一个正数(signum = 1)
原文:
您可以只在数组前加上一个零字节:
byte[] original = new byte[] { (byte) 255 };
System.out.println(new BigInteger(original).toString()); // prints "-1"
byte[] paddedCopy = new byte[original.length + 1];
for (int i = 0; i < original.length; i++) {
paddedCopy[i + 1] = original[i];
}
System.out.println(new BigInteger(paddedCopy).toString()); // prints "255"
这实际上会使符号位无效,使数字无符号。
我正在寻找一种方法,如何将任意长度的 byte[] 可逆地转换为 positive 数字(数字中的字符串表示形式)。
BigInteger 提供了一个解决方案:
byte[] originalBytes = ...
String string = new BigInteger(originalBytes).toString();
...
byte[] decodedBytes = new BigInteger(string).toByteArray();
但是,我不确定如何优雅地去除负值(或在何处存储符号)并保持过程可逆。
编辑: 只需替换
String string = new BigInteger(originalBytes).toString();
和
String string = new BigInteger(1, originalBytes).toString();
1,
表示传递的数组代表一个正数(signum = 1)
原文:
您可以只在数组前加上一个零字节:
byte[] original = new byte[] { (byte) 255 };
System.out.println(new BigInteger(original).toString()); // prints "-1"
byte[] paddedCopy = new byte[original.length + 1];
for (int i = 0; i < original.length; i++) {
paddedCopy[i + 1] = original[i];
}
System.out.println(new BigInteger(paddedCopy).toString()); // prints "255"
这实际上会使符号位无效,使数字无符号。