我正在尝试将以下 python 代码移植到 c#
import os
import sys
import ctypes
FNV32_PRIME = 0xB3CB2E29
FNV32_BASIS = 0x319712C3
def uint32(v):
return ctypes.c_uint32(v).value
def fnv1a_hash(data):
hval = FNV32_BASIS
for i in range(0, len(data)):
hval = uint32(hval ^ data[i])
hval = uint32(hval * FNV32_PRIME)
return hval
print("starting")
if len(sys.argv) == 2:
input_file_path = sys.argv[1]
else: input_file_path = "dvars.txt"
with open(input_file_path, "r") as input_file:
for dvar_name in input_file:
dvar_name = dvar_name.rstrip("\r\n")
dvar_hash_1 = dvar_name.lower() + '\x00'
dvar_hash_2 = bytearray(dvar_hash_1.encode("ascii"))
dvar_hash = fnv1a_hash(dvar_hash_2)
final = "%-30s = 0x%08X" % (dvar_name, dvar_hash)
print(final)
print("done")
效果很好:
starting
con_gameMsgWindow0MsgTime = 0xFC60C821
到目前为止我得到了这个:
public static class Extensions
{
private const UInt32 FnvPrime = 0xB3CB2E29;private const UInt32 FnvOffsetBasis = 0x319712C3;
public static string ToHashFnv1a32(this string text, Fnv1a32 hasher = null)
{
var bytes_encoded = Encoding.UTF8.GetBytes(text); // +'\x00'
if (hasher is null) hasher = new Fnv1a32(fnvPrime: FnvPrime, fnvOffsetBasis: FnvOffsetBasis);
var byte_hash = hasher.ComputeHash(bytes_encoded);
// int decValue = int.Parse(t, System.Globalization.NumberStyles.HexNumber);
var uint32 = BitConverter.ToUInt32(byte_hash, 0);
var uint32_hex = string.Format("{0:X}", uint32);
var uint32_dec = string.Format("{0:D}", uint32);
var stringg = BitConverter.ToString(byte_hash).Replace("-", "");
var expected_hex = string.Format("{0:X}", 0xFC60C821);
var expected_dec = string.Format("{0:D}", 0xFC60C821);
return byte_hash.ToString(); //
}
}
我真的把头撞在了桌子上,因为我似乎无法弄清楚为什么它没有计算出正确的哈希值(我正在使用 允许我更改基数和偏移量)
富国沪深
相关分类