PMPの流儀

我が家の流儀

我が家で気になったことを夫婦で取り上げていきます

MENU

PowerShell 数値の2進数文字列 取得関数(パイプライン対応)

PowerShell で数値を2進数文字列に変換する関数を紹介します。桁数合わせや間にスペースを入れて見やすくしています。最終形態はPowerShellらしくパイプラインに対応します。

1. 単純な例

PowerShellで2進数文字列を取得するには .Net Framework の Convert クラスを使用します。以下は0x12の2進数文字列化の例です。

[Convert]::ToString(0x12,2)

実行結果

10010

これで間違ってはいないのですが、文字列にする場合は大抵16bitや32bit分に桁を合わせて出力する事が多いので、出力フォーマットが指定できないのが痛いです。

2. 自作関数

表示桁数(ビット数)の指定と、1バイト(8桁)ずつスペースで区切る関数を作成しました

Function Get-Int2BinStr([int]$x, [int]$bit)
{
    [string] $s = '';

    [int]$b = 1
    for([int]$i=0; $i -lt $bit; $i++) {
        if($i) {
            if($i % 8 -eq 0 ) {
                $s = ' ' + $s;
            }
        }
        if( $x -band $b ) {
            $s = '1' + $s;
        } else {
            $s = '0' + $s;
        }
        $b = $b -shl 1;
    }
    return $s;
}

呼び出し例 0x12を16bit幅で2進数文字列化

Get-Int2BinStr 0x12, 16

実行結果

00000000 00010010

見やすいですね。

3. パイプライン対応版

PowerShellらしくパイプラインに対応させます。

Function Get-Int2BinStr
{
    param(
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        [int] $x,
        [int] $bit
    )
    process
    {
        [string] $s = '';

        [int]$b = 1
        for([int]$i=0; $i -lt $bit; $i++) {
            if($i) {
                if($i % 8 -eq 0 ) {
                    $s = ' ' + $s;
                }
            }
            if( $x -band $b ) {
                $s = '1' + $s;
            } else {
                $s = '0' + $s;
            }
            $b = $b -shl 1;
        }
        return $s;
    }
}

実行例 0x10から0x12まで16bit幅で2進数文字列出力

0x10..0x12 | Get-Int2BinStr -bit 16
00000000 00010000
00000000 00010001
00000000 00010010

数値をパイプでインプットできるようになり、応用範囲が広がります。