我正在寻找一种方法,如何将任意长度的byte []可逆地转换为正数字(数字中的字符串表示)。
BigInteger提供了解决方案:
void write_log(FILE * fp, char * event, ...)
{
va_list list;
va_start(list, event);
// Cannot use va_arg(list, type_of_var) here!!!
}
但是,我不确定如何优雅地摆脱负值(或存储标志的位置)并保持流程可逆。
答案 0 :(得分:3)
编辑:只需替换
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"
这将使符号位基本无效,使数字无符号。