文字列をバイナリに変換

文字列をバイナリに変換する方法について調べてみたいと思います。まずはPowerShellにおいてデータ変換のコマンドレッドが存在するか確認してみます。ヘルプでconvertで引っかかるものは以下でした。

ConvertTo−Html
ConvertFrom−StringData
ConvertTo−CSV
ConvertFrom−CSV
ConvertTo−XML
Convert−Path
ConvertFrom−SecureString
ConvertTo−SecureString
バイナリに変換できそうなコマンドレットは無さそうです。そこで、ググって検索してみます。その結果、.NETでSystem.Text.Encodingというクラスが存在することがわかりました。System.Text.Encodingのメンバーを確認してみます。−staticは静的プロパティおよびメソッドを表示するという意味です。

PS C:\Users\sinpay> [system.text.encoding] | get−member −static


   TypeName: System.Text.Encoding

Name             MemberType Definition
−−−−             −−−−−−−−−− −−−−−−−−−−
Convert          Method     static byte Convert(System.Text.Encoding srcEncoding, System.Text.Encoding dstEncoding...
Equals           Method     static bool Equals(System.Object objA, System.Object objB)
GetEncoding      Method     static System.Text.Encoding GetEncoding(int codepage), static System.Text.Encoding GetEn...
GetEncodings     Method     static System.Text.EncodingInfo
 GetEncodings()
ReferenceEquals  Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
ASCII            Property   static System.Text.Encoding ASCII {get;}
BigEndianUnicode Property   static System.Text.Encoding BigEndianUnicode {get;}
Default          Property   static System.Text.Encoding Default {get;}
Unicode          Property   static System.Text.Encoding Unicode {get;}
UTF32            Property   static System.Text.Encoding UTF32 {get;}
UTF7             Property   static System.Text.Encoding UTF7 {get;}
UTF8             Property   static System.Text.Encoding UTF8 {get;}

ASCII、Unicode、UTF8等のプロパティが存在します。(shift−jisがありません) また、これらのプロパティはそれぞれASCIIタイプ、Unicodeタイプ、UTF8タイプ等を呼び出していることがわかります。ASCIIタイプのメンバーを表示してみます。ASCIIプロパティは静的なメンバーのため「::」で指定します。

PS C:\Users\sinpay> [system.text.encoding]::ASCII | get−member


   TypeName: System.Text.ASCIIEncoding

Name               MemberType Definition
−−−−               −−−−−−−−−− −−−−−−−−−−
Clone              Method     System.Object Clone()
Equals             Method     bool Equals(System.Object value)
GetByteCount       Method     int GetByteCount(string chars), int GetByteCount(System.Char*, mscorlib, Version=2.0.0...
GetBytes           Method     int GetBytes(System.Char*, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=...
GetCharCount       Method     int GetCharCount(byte bytes, int index, int count), int GetCharCount(System.Byte*, m...
GetChars           Method     int GetChars(byte
 bytes, int byteIndex, int byteCount, char chars, int charIndex),...
GetDecoder         Method     System.Text.Decoder GetDecoder()
GetEncoder         Method     System.Text.Encoder GetEncoder()
GetHashCode        Method     int GetHashCode()
GetMaxByteCount    Method     int GetMaxByteCount(int charCount)
GetMaxCharCount    Method     int GetMaxCharCount(int byteCount)
GetPreamble        Method     byte
 GetPreamble()
GetString          Method     string GetString(byte bytes, int byteIndex, int byteCount), string GetString(byte ...
GetType            Method     type GetType()
IsAlwaysNormalized Method     bool IsAlwaysNormalized(), bool IsAlwaysNormalized(System.Text.NormalizationForm form)
ToString           Method     string ToString()
BodyName           Property   System.String BodyName {get;}
CodePage           Property   System.Int32 CodePage {get;}
DecoderFallback    Property   System.Text.DecoderFallback DecoderFallback {get;set;}
EncoderFallback    Property   System.Text.EncoderFallback EncoderFallback {get;set;}
EncodingName       Property   System.String EncodingName {get;}
HeaderName         Property   System.String HeaderName {get;}
IsBrowserDisplay   Property   System.Boolean IsBrowserDisplay {get;}
IsBrowserSave      Property   System.Boolean IsBrowserSave {get;}
IsMailNewsDisplay  Property   System.Boolean IsMailNewsDisplay {get;}
IsMailNewsSave     Property   System.Boolean IsMailNewsSave {get;}
IsReadOnly         Property   System.Boolean IsReadOnly {get;}
IsSingleByte       Property   System.Boolean IsSingleByte {get;}
WebName            Property   System.String WebName {get;}
WindowsCodePage    Property   System.Int32 WindowsCodePage {get;}

GetBytesというメソッドが存在します。これは引数に指定した文字のコードを返します。実際に使ってみると以下になります。

PS C:\Users\sinpay> [system.text.encoding]::ASCII.getbytes("a")
97

出力されるデータは10進数です。そのため2進数に変換する処理が必要です。また、ググって調べてみました。すると.NETの静的メソッドでConvert.ToString メソッド (Int32, Int32)というものがありました。これは、32 ビット符号付き整数の値を、指定した基数で等価の String 形式に変換します。 例えば10進数の97を2進数に変換するには以下のようにします。

PS C:\Users\sinpay> [system.convert]::tostring(97,2)
1100001

以上を使って、文字列をバイナリに変換するプログラムを作成してみます。

set-PSDebug -strict
    
# ------------------------------------------
# 文字列をバイナリに変換する
# ------------------------------------------
function StrToBinary {            
    # 引数を取得する
    param([string]$str)
        
    # 文字コード"ASCII","Unicode"でまわす
    foreach ( $code_type in "ASCII","Unicode"){
        # 変数の初期化
        $code_dec_array = @()
        $code_bin_str = ""
    
        # 10進数の文字コードを配列に取得
        $code_dec_array += [system.text.encoding]::$code_type.getbytes($str)
        
        
        # 2進数に変換した文字コードをString型で取得
        foreach ($code in $code_dec_array){
            [string]$code_bin_str += [String]::format("{0:00000000}",[int][system.convert]::tostring($code,2)) + " "
        }
        
        # 画面に表示
        $code_type_line = "[" + $code_type + "]"
        write-host  $code_type_line
        write-host  $code_bin_str
    }    
}


実行結果は以下のようになります。

PS C:\Users\sinpay\Documents\work\powershell\20091211_shell> . .\StrToBinary.ps1
PS C:\Users\sinpay\Documents\work\powershell\20091211_shell> StrToBinary "abcde"
[ASCII]
01100001 01100010 01100011 01100100 01100101
[Unicode]
01100001 00000000 01100010 00000000 01100011 00000000 01100100 00000000 01100101 00000000
PS C:\Users\sinpay\Documents\work\powershell\20091211_shell>