[英]Convert array of doubles to byte array: What is the Java way of C# Buffer.BlockCopy?
我需要将Java中的double数组序列化为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相同!
当方法上的数组类型不是相同的原语时,您将获得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;
}
}
Double.SIZE得到64,这是我建议像这样初始化数组的位数
Byte[] bytes = new Byte[abundaceArray.length * 8];
不确定此C#函数的作用,但我怀疑您应该替换此行
System.arraycopy(abundaceArray, 0, bytes, 0, bytes.length);
有了这个
System.arraycopy(abundaceArray, 0, bytes, 0, abundaceArray.length);
我猜您正在使用apache commons Base64类。 那只有接受字节数组(原始类型)的方法,而不接受字节(原始类型周围的对象包装器)的方法。
目前尚不清楚您的“ abundaceArray”是什么类型-是双精度型还是双精度型。
无论哪种方式,您都不能使用System.arraycopy在不同原始类型的数组之间进行复制。
我认为最好的选择是将数组对象序列化为字节数组,然后对它进行base64编码。
例如:
ByteArrayOutputStream b = new ByteArrayOutputStream(); // to store output from serialization in a byte array
ObjectOutputStream o = new ObjectOutputStream(b); // to do the serialization
o.writeObject(abundaceArray); // arrays of primitive types are serializable
String abundanceValues = Base64.encodeBase64String(b.toByteArray());
当然,在另一端有一个ObjectInputStream可以用于另一个方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.