转换双精度数组到字节数组:c# Buffer.BlockCopy的Java方式是什么?
本文关键字:数组 Java 方式 是什么 BlockCopy Buffer 双精度 到字节 转换 | 更新日期: 2023-09-27 18:09:02
我需要在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中实现这一点?
编辑:缓冲区。BlockCopy在字节级别复制,最后一个参数是字节数。系统。Arraycopy最后一个参数是要复制的元素个数。是的,应该是丰度数组。
EDIT2:
base64字符串必须与c#代码创建的行相同!
当方法上的数组类型不是相同的原语时,您将得到ArrayStoreException,因此double to byte将不起作用。这是一个变通办法,我修补,似乎工作。我不知道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;
}
}
The 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类。它的方法只接受字节数组(基本类型),而不接受字节数组(基本类型的对象包装)。
不清楚你的'丰度数组'是什么类型-无论是双精度还是双精度。
无论哪种方式,都不能使用System。
在不同基本类型的数组之间拷贝。我认为你最好的选择是序列化你的数组对象为字节数组,然后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在另一端的另一个方向。