Search code examples
powershellcrc32

How to calculate the CRC32 of a string in Powershell?


I could not find any simple Powershell-function to calculate the CRC32 of a given string. Therefore I decided to write my own function which I would like to share in my answer.


Solution

  • Based on the good input from @Cem Polat here a more elegant solution with embededd code:

    $crc32 = add-type '
    [DllImport("ntdll.dll")]
    public static extern uint RtlComputeCrc32(uint dwInitial, byte[] pData, int iLen);
    ' -Name crc32 -PassThru
    
    $str = "123456789"
    $arr = [System.Text.Encoding]::UTF8.GetBytes($str)
    $crc = $crc32::RtlComputeCrc32(0, $arr, $arr.Count)
    $crc.ToString("X8")