我需要用Java将一个双倍数组序列化为base64。我有来自C#的以下方法
public static string DoubleArrayToBase64( double[] dValues ) {
byte[] bytes = new byte[dValues.Length * sizeof( double )];
Buffer.BlockCopy( dValues, 0, bytes, 0, bytes.Length );
return Convert.ToBase64String( bytes );
}
我如何在Java中做到这一点?我试过了
Byte[] bytes = new Byte[abundaceArray.length * Double.SIZE];
System.arraycopy(abundaceArray, 0, bytes, 0, bytes.length);
abundanceValues = Base64.encodeBase64String(bytes);
然而,这会导致IndexOutofBoundsException。
我如何在Java中实现这一点?
编辑:
Buffer.BlockCopy在字节级复制,最后一个参数是字节数。System.arraycopy最后一个参数是要复制的元素数。所以是的,应该是abundaceArray.length,但是会抛出一个ArrayStoreException。
EDIT2:
base64字符串必须与用c#代码创建的ine相同!
发布于 2014-06-17 04:42:16
当方法上的数组类型不是相同的原语时,就会得到一个ArrayStoreException,因此双字节不能工作。这是我修补过的一个解决办法,它似乎很有效。我不知道java核心中有任何方法可以自动将原语转换为字节块:
public class CUSTOM {
public static void main(String[] args) {
double[] arr = new double[]{1.1,1.3};
byte[] barr = toByteArray(arr);
for(byte b: barr){
System.out.println(b);
}
}
public static byte[] toByteArray(double[] from) {
byte[] output = new byte[from.length*Double.SIZE/8]; //this is reprezented in bits
int step = Double.SIZE/8;
int index = 0;
for(double d : from){
for(int i=0 ; i<step ; i++){
long bits = Double.doubleToLongBits(d); // first transform to a primitive that allows bit shifting
byte b = (byte)((bits>>>(i*8)) & 0xFF); // bit shift and keep adding
int currentIndex = i+(index*8);
output[currentIndex] = b;
}
index++;
}
return output;
}
}
发布于 2014-06-17 05:19:02
Double.SIZE get 64,这是我建议像这样初始化数组的位数
Byte[] bytes = new Byte[abundaceArray.length * 8];
发布于 2014-06-17 04:27:57
不确定这个C#函数做什么,但我怀疑您应该替换这一行
System.arraycopy(abundaceArray, 0, bytes, 0, bytes.length);
有了这个
System.arraycopy(abundaceArray, 0, bytes, 0, abundaceArray.length);
https://stackoverflow.com/questions/24263713
复制