如何在Powershell中计算字符串的CRC32?

问题描述 投票:0回答:1

我找不到任何简单的 Powershell 函数来计算给定字符串的 CRC32。 因此,我决定编写自己的函数,我想在我的答案中分享它。

powershell crc32
1个回答
0
投票

这里是 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秒)。

© www.soinside.com 2019 - 2024. All rights reserved.