簡體   English   中英

如何將Base64字符串轉換為float數組或int數組?

[英]How can I convert a Base64 string to a float array or int array?

我有一些代碼將float[]轉換為Base64字符串:

float[] f_elements = <from elsewhere in my code>;
byte[] f_vfeat = f_elements.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
string f_sig = Convert.ToBase64String(f_vfeat);

基本上也有將int[]轉換為Base64字符串的相同代碼:

int[] i_elements = <from elsewhere in my code>;
byte[] i_feat = i_elements.SelectMany(value => BitConverter.GetBytes(value)).ToArray();
string i_sig = Convert.ToBase64String(i_feat);

兩者均產生預期的Base64字符串。 但是,現在我需要解碼回數組,並且遇到了麻煩。

如何從我的Base64字符串中獲取原始數據數組。 在解碼Base64字符串之前,我會知道它應該是int[]還是float[] ,所以我認為這會有所幫助。

有誰知道該怎么辦從Base64字符串到float[]int[]嗎?

您可以使用BitConverter.ToInt32BitConverter.ToSingle轉換數組的一部分:

byte[] bytes = Convert.FromBase64String();
int[] ints = new int[bytes.Length / 4];
for (int i = 0; i < ints.Length; i++)
{
    ints[i] = BitConverter.ToInt32(bytes, i * 4);
}

(當然,與ToSingle等效)。

在我看來,很遺憾GetBytes沒有將字節直接寫到現有數組中的重載,而不是在每次調用時都創建一個新數組。

Convert.FromBase64String有什么問題嗎?

byte[] i_feat = Convert.FromBase64String(i_sig)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM