Wanted:返回UInt16的C#哈希算法

本文关键字:哈希 算法 UInt16 返回 Wanted | 更新日期: 2023-09-27 18:26:39

我需要一个散列算法,它接受一个字符串并返回一个可以存储在UInt16中的数字。我需要它来计算一个小的校验和数。

.Net对此有算法吗?

Wanted:返回UInt16的C#哈希算法

也许您正在寻找crc16。这里有一个使用byte[]作为输入的示例,也许您可以修改它来处理字符。


为下一个人添加了一些代码:
用法:ushort hash = Crc16.ComputeHash("Hello World!");

using System;
/// <summary>
/// Creates a checksum as a ushort / UInt16.
/// </summary>
public class Crc16
{
    const ushort polynomial = 0xA001;
    ushort[] table = new ushort[256];
    /// <summary>
    /// Initializes a new instance of the <see cref="Crc16"/> class.
    /// </summary>
    public Crc16()
    {
        ushort value;
        ushort temp;
        for (ushort i = 0; i < table.Length; ++i)
        {
            value = 0;
            temp = i;
            for (byte j = 0; j < 8; ++j)
            {
                if (((value ^ temp) & 0x0001) != 0)
                {
                    value = (ushort)((value >> 1) ^ polynomial);
                }
                else
                {
                    value >>= 1;
                }
                temp >>= 1;
            }
            table[i] = value;
        }
    }
    /// <summary>
    /// Computes the hash.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <returns></returns>
    public static ushort ComputeHash(string input)
    {
        if(input == null)
        {
            input = "";
        }
        Crc16 crc = new Crc16();
        byte[] bytes = Encoding.UTF8.GetBytes(input);
        return crc.ComputeChecksum(bytes);
    }
    /// <summary>
    /// Computes the checksum.
    /// </summary>
    /// <param name="bytes">The bytes.</param>
    /// <returns>The checkum.</returns>
    public ushort ComputeChecksum(byte[] bytes)
    {
        ushort crc = 0;
        for (int i = 0; i < bytes.Length; ++i)
        {
            byte index = (byte)(crc ^ bytes[i]);
            crc = (ushort)((crc >> 8) ^ table[index]);
        }
        return crc;
    }
    /// <summary>
    /// Computes the checksum bytes.
    /// </summary>
    /// <param name="bytes">The bytes.</param>
    /// <returns>The checksum.</returns>
    public byte[] ComputeChecksumBytes(byte[] bytes)
    {
        ushort crc = ComputeChecksum(bytes);
        return BitConverter.GetBytes(crc);
    }
}

好吧,我会咬一口:

int hash = "hello".GetHashCode();
ushort hash16 = (ushort) ((hash >> 16) ^ hash);

当然,如果你真的想的话,你也可以写自己的哈希,但这似乎已经足够方便了。

.Net对此有算法吗?

没有

请查看哈希函数以查看您要查找的内容。了解差异,选择适合你需求的,你的帖子很"短",我不能说太多。在任何情况下,我都不建议你采用32位算法的输出,只采用较低的16位,这是一个糟糕的选择。

你在寻找CRC校验和吗,你在寻找正常校验和吗?

无论哪种方式,都可以选择,在谷歌上搜索C# <the implementation name>,并根据自己的喜好进行修改。