之前已经多次回答了一般方法,但是我的实现方法存在问题,但是我想看看一个好的读者是否可以找到我出错的地方.
代码和测试是;
[TestMethod]
public void FloatConversion()
{
// Set up some test data
int repetitions = 100000;
Random rand = new Random();
float[] testSetOfFloats = new float[repetitions];
for (int count = 0; count < repetitions; count++)
{
testSetOfFloats[count] = rand.NextFloat(0, float.MaxValue);
}
// Convert the floats into a byte array
byte[] floatsAsByteArray = new byte[repetitions * 4]; // 4 bytes for a Single
for (int count = 0; count < repetitions; count++)
{
byte[] floatAsBytes = BitConverter.GetBytes(testSetOfFloats[count]);
floatAsBytes.CopyTo(floatsAsByteArray, count * 4);
}
// Convert the byte array to a Unicode string
string serialisedByteArray = System.Text.Encoding.Unicode.GetString(floatsAsByteArray);
// ... Do some work, store the string, re-read the string, then ...
// Convert the unicode string back into a byte array
byte[] deserializedByteArray = System.Text.Encoding.Unicode.GetBytes(serialisedByteArray);
// Convert the byte array back into an array of floats
float[] deserializedFloats = new float[repetitions];
for (int count = 0; count < repetitions; count++)
{
int offset = count * 4;
deserializedFloats[count] = BitConverter.ToSingle(deserializedByteArray, offset);
}
for (int count = 0; count < repetitions; count++)
{
// This will fail - but many will pass the test.
Assert.IsTrue(deserializedFloats[count] == testSetOfFloats[count]);
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的非标准方法是Random NextFloat()的扩展,它只返回传递的值范围内的随机Single.
//将字节数组转换为Unicode字符串
string serialisedByteArray = System.Text.Encoding.Unicode.GetString(floats);
Run Code Online (Sandbox Code Playgroud)
您正在将浮点数转换为字节,然后将其转换为字符串...麻烦的处方.
有一些字节序列(查找代理对,高代理无效,如果没有低代理,反之亦然),它们不是有效的UCS-2字符串,因此可能无法"幸存"从字节的往返[]串起来然后回来.
问题是:为什么要将二进制数据1:1转换为字符串?如果您需要将二进制文件作为字符串传输,可以选择许多编码,例如base64.