gpt4 book ai didi

c# - 通缉 : C# hash algorithm that returns UInt16?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:27 30 4
gpt4 key购买 nike

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

.Net 有这方面的算法吗?

最佳答案

也许您正在寻找crc16 . Here是一个使用 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);
}
}

关于c# - 通缉 : C# hash algorithm that returns UInt16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26400869/

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