You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

自定义PowerShell CRC32计算函数

找了一圈没发现能直接用的简易PowerShell CRC32计算函数,索性自己写了一个,分享给需要的人:

function Get-CRC32 {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, ValueFromPipeline=$true)]
        [string]$InputString
    )

    begin {
        # 初始化CRC32校验表
        $crcTable = New-Object byte[] 256
        for ($i = 0; $i -lt 256; $i++) {
            $crc = $i
            for ($j = 0; $j -lt 8; $j++) {
                if ($crc -band 1) {
                    $crc = ($crc -shr 1) -bxor 0xEDB88320
                } else {
                    $crc = $crc -shr 1
                }
            }
            $crcTable[$i] = $crc -band 0xFF
        }
    }

    process {
        $crc = 0xFFFFFFFF
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($InputString)
        foreach ($byte in $bytes) {
            $lookupIndex = ($crc -band 0xFF) -bxor $byte
            $crc = ($crc -shr 8) -bxor [System.BitConverter]::ToUInt32($crcTable, $lookupIndex * 4)
        }
        $crc = $crc -bxor 0xFFFFFFFF
        # 返回8位小写十六进制格式结果
        return $crc.ToString("x8")
    }
}

用法示例

  • 直接传参计算:
    Get-CRC32 -InputString "Hello World"
    
  • 支持管道输入:
    "Test String" | Get-CRC32
    

函数默认用UTF-8编码解析字符串,你可以根据需求把[System.Text.Encoding]::UTF8改成其他编码(比如ASCII)。

内容的提问来源于stack exchange,提问作者Carsten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:13:11