简体   繁体   中英

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

I have some code that converts a float[] to a Base64 string:

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);

I also have - basically - the same code that converts an int[] to a Base64 string:

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);

Both of these produce Base64 strings as expected. However, now I need to decode back to an array, and I'm running into trouble.

How can I go from my Base64 string(s), and get the original data array(s). Before I decode the Base64 string, I will know if it is suppose to be an int[] or float[] , so I think that will help.

Does anyone know how to do go from Base64 string to float[] or int[] ?

You can use BitConverter.ToInt32 or BitConverter.ToSingle to convert part of an array:

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);
}

(And the equivalent for ToSingle , of course.)

In my view, it's a shame that GetBytes doesn't have an overload to write the bytes directly into an existing array, instead of creating a new array on each call...

Convert.FromBase64String有什么问题吗?

byte[] i_feat = Convert.FromBase64String(i_sig)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM