[英]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.