简体   繁体   English

如何比较 c# 中逻辑上相等但技术上不相等的字节数组( byte[] )?

[英]How to compare logically equal, but technically unequal byte-arrays ( byte[] ) in c#?

I have two large byte-arrays (byte[]) that I want need to compare.我有两个需要比较的大字节数组 (byte[])。 They should by logically equal but are not always technically equal.它们在逻辑上应该相等,但在技术上并不总是相等。 The reason being differences in how floating point numbers are represented in these two arrays.原因是这两个 arrays 中浮点数的表示方式不同。

Is there a way of comparing these by idenfitying the floating point numbers and testing if the numbers are within a error tolerance?有没有办法通过识别浮点数并测试这些数字是否在容错范围内来比较这些?

I suspect this situation is caused by the fact that one of these byte-arrays has been stored and retreived from a database (postgres).我怀疑这种情况是由于这些字节数组之一已被存储并从数据库(postgres)中检索到的。

So far I compare the two byte arrays like so:到目前为止,我比较了两个字节 arrays ,如下所示:

public static bool AreEqual(byte[] a, byte[] b)
{
    if (a.Length == b.Length)
    {
        for (var i = 0; i < a.Length; ++i)
        {
            if (a[i] != b[i])
            {
                return false;
            }
        }
    }

    return true;
}

(Initially I serialized to JSON, but I had the same problem with that. Thought serializing to bytes would fix this, but no). (最初我序列化为 JSON,但我遇到了同样的问题。认为序列化为字节可以解决这个问题,但没有)。

First you need to convert your byte arrays to float arrays, if that is what they represent.首先,您需要将字节 arrays 转换为浮动 arrays,如果这就是它们所代表的。 You can either use a binary reader , or you could convert your array to a span, cast it , and copy the result to a new array.您可以使用二进制阅读器,也可以将数组转换为跨度, 对其进行强制转换,然后将结果复制到新数组。

For comparison Linq has a SequenceEquals method that compares all the individual values, and allows for a equality comparer to specify how that comparison is made.对于比较 Linq 有一个SequenceEquals方法来比较所有单独的值,并允许相等比较器指定如何进行比较。

You need to implement this equality comparer yourself, after reading about how floating point numbers should be compared.在阅读了应该如何比较浮点数之后,您需要自己实现这个相等比较器。 See Floating point guide and how to compare floating point numbers请参阅浮点指南以及如何比较浮点数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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