C# 如何计算从文件中提取的六进制值的熵?

C# 如何计算从文件中提取的六进制值的熵?,c#,hex,entropy,C#,Hex,Entropy,我使用此代码计算十六进制值的熵 public static double ShannonEntropy(string s) { string[] hexValuesSplit = s.Split(' '); var map = new Dictionary<int, int>(); foreach (String hex in hexValuesSplit) { int value = Convert.ToInt32(hex, 16

我使用此代码计算十六进制值的熵

public static double ShannonEntropy(string s)
{
    string[] hexValuesSplit = s.Split(' ');

    var map = new Dictionary<int, int>();

    foreach (String hex in hexValuesSplit)
    {
        int value = Convert.ToInt32(hex, 16);

        if (!map.ContainsKey(value))
            map.Add(value, 1);
        else
            map[value] += 1;

    }

    double result = 0.0;
    int len = s.Length;
    foreach (var item in map)
    {
        var frequency = (double)item.Value / len;
        result -= frequency * (Math.Log(frequency) / Math.Log(2));
    }

    return result;
}
公共静态双香农熵(字符串s)
{
字符串[]hexValuesSplit=s.Split(“”);
var map=newdictionary();
foreach(hexValuesSplit中的字符串十六进制)
{
int值=转换为32(十六进制,16);
如果(!map.ContainsKey(值))
地图。添加(值,1);
其他的
映射[值]+=1;
}
双结果=0.0;
int len=s.长度;
foreach(映射中的变量项)
{
变量频率=(双)项值/长度;
结果-=frequency*(Math.Log(frequency)/Math.Log(2));
}
返回结果;
}
十六进制值类似于“4D 5A 68 6B 6A 68 6A 00 02 00 00 FF” 我检查了s。返回的长度不正确!
为什么熵的结果不正确?

因为
s.Length
不是集合中的项数
hexValuesSplit.Length
这能解决我的问题吗,因为
s.Length
不是集合中的项目数
hexValuesSplit.Length
会是Anks,这就解决了我的问题