gpt4 book ai didi

c# - 将 float[] 转换为字符串并返回 float[] - 测试失败,但我不明白为什么

转载 作者:太空宇宙 更新时间:2023-11-03 19:05:37 24 4
gpt4 key购买 nike

一般的方法之前已经回答过多次,但是我的实现有一个问题失败了,我想看看好心的读者是否能发现我哪里出错了。

代码和测试是;

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

唯一的非标准方法是对 Random NextFloat() 的扩展,它只从传递的值范围中返回一个随机 Single。

最佳答案

// Convert the byte array to a Unicode string

    string serialisedByteArray = System.Text.Encoding.Unicode.GetString(floats);

您正在将 float 转换为字节,然后将其转换为字符串……这是麻烦的根源。

有某些字节序列(查找代理项对,如果后面没有低代理项,则高代理项无效,反之亦然),它们不是有效的 UCS-2 字符串,因此可能无法“存活”轮次-从 byte[] 到字符串再返回。

因此问题来了:为什么要把二进制数据1:1转换成字符串呢?如果您需要将二进制文件作为字符串传输,有多种编码可供选择,例如base64.

关于c# - 将 float[] 转换为字符串并返回 float[] - 测试失败,但我不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28231491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com