PowerShell で数値を2進数文字列に変換する関数を紹介します。桁数合わせや間にスペースを入れて見やすくしています。最終形態はPowerShellらしくパイプラインに対応します。 PowerShellで2進数文字列を取得するには .Net Framework の Convert クラスを使用します。以下は0x12の2進数文字列化の例です。 実行結果 これで間違ってはいないのですが、文字列にする場合は大抵16bitや32bit分に桁を合わせて出力する事が多いので、出力フォーマットが指定できないのが痛いです。 表示桁数(ビット数)の指定と、1バイト(8桁)ずつスペースで区切る関数を作成しました 呼び出し例 0x12を16bit幅で2進数文字列化 実行結果 見やすいですね。 PowerShellらしくパイプラインに対応させます。 実行例
0x10から0x12まで16bit幅で2進数文字列出力 数値をパイプでインプットできるようになり、応用範囲が広がります。
1. 単純な例
[Convert]::ToString(0x12,2)
10010
2. 自作関数
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;
}
Get-Int2BinStr 0x12, 16
00000000 00010010
3. パイプライン対応版
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 | Get-Int2BinStr -bit 16
00000000 00010000
00000000 00010001
00000000 00010010