1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PowerShell 7のCRC32クラスと作成時の覚書

Last updated at Posted at 2020-08-01

PowerShell 7でCRC32の計算機能を提供するクラスのサンプルコードとその作成時に学んだことの覚書きです。

CRC32クラスのソースコード

class CRC32 {
  [uint[]]$CrcTable

  CRC32() {
    $this.CrcTable = [uint[]]::CreateInstance([uint], 256);
    for ([uint]$n = 0; $n -lt 256; $n++)
    {
        [uint]$c = $n;
        for ([uint]$k = 0; $k -lt 8; $k++)
        {
            $c = (($c -band 1) -ne 0) ? (0xedb88320u -bxor ($c -shr 1)) : ($c -shr 1);
        }
        $this.CrcTable[$n] = $c;
    }
  }

  [uint]Calculate([byte[]]$array) {
    return $this.Calculate($array, 0, $array.Length)
  }

  [uint]Calculate([byte[]]$array, [int]$start) {
    return $this.Calculate($array, $start, $array.Length)
  }

  [uint]Calculate([byte[]]$array, [int]$start, [int]$length) {
      if ($start -lt 0) {
        throw [ArgumentOutOfRangeException]::New();
      }
      if ($length -lt 0) {
        $length = $array.Length - $start;
      }

      [uint]$c = 0xffffffffu;
      for ([uint]$n = 0; $n -lt $length; $n++) {
          $c = $this.CrcTable[($c -bxor $array[$start + $n]) -band 0xff] -bxor ($c -shr 8);
      }
      return $c -bxor 0xffffffffu;
  }
}

$Crc32 = [CRC32]::New()
$Crc32.Calculate([byte[]](0x00, 0x01, 0x02)).ToString("X08")

覚書き

  • 全般事項
    • 変数は$var。大小演算子は-lt(<)、`-gt`(>)。
    • ビット論理演算は-bor-band-bxor。論理演算-or-and-xorとは異なる。
    • ビットシフト演算子は-shl-shr
    • リテラルの型はサフィックスで指定。uintのサフィックスはu
    • クラスのインスタンス作成は[ClassName]::New()
    • 長さを指定した特定型の配列作成は[type[]]::CreateInstance([type], length)。例えば[uint[]]::CreateInstance([uint], 256)
    • 値を指定した特定型の配列作成は[type[]](...)。例えば[byte[]](0x00, 0x01, 0x02)
  • クラス関係の注意
    • クラスはclass ClassName {...}で作成。
    • コンストラクタはクラス名と同名の関数ClassName() {...}
    • クラスのメンバ変数はclass ClassName {...}...[type]$nameとして宣言。
    • クラスのメンバ変数は引数の既定値が指定不可能(paramを指定できない)。ただし、オーバーロード可能。
    • クラスのメンバ関数はオーバーロードできる。例えば関数f() {...}f([int]x) {...}f([int]x, [int]y) {...}を同時に定義できる。
    • クラス内で自身のメンバ変数、メンバ関数は$this.nameで参照。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?