我找不到任何简单的 Powershell 函数来计算给定字符串的 CRC32。 因此,我决定编写自己的函数,我想在我的答案中分享它。
这里是 CRC32 函数:
function CRC32($str) {
$crc = [uint32]::MaxValue
$poly = [uint32]0xEDB88320L
$bytes = [System.Text.Encoding]::UTF8.GetBytes($str)
foreach ($byte in $bytes) {
$crc = ($crc -bxor $byte)
foreach ($bit in 0..7) {$crc = ($crc -shr 1) -bxor ($poly * ($crc -band 1))}
}
return [uint32]::MaxValue - $crc
}
$str = "123456789"
$crc32 = CRC32 $str
Write-Host "CRC32 of '$str' is: 0x$($crc32.ToString("X8"))"
我决定跳过查找表的创建,这意味着我必须为每个字节执行按位循环。因此它应该主要用于较短的字符串(长度为1MB的字符串的计算时间仍然低于1秒)。