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で参照。
- クラスは