header
CodePanic! > C#.NET Tips > 今ここ

■ASCII文字コードを取得する

任意の文字のACSII文字コードを取得する方法です。
C#,VB,VCそれぞれの方法もありますし
.NET Frameworkを使った方法にも何通りかあるようです。

System.Text.Encoding.GetEncoding    C#,VBの例参照
System.Text.Encoding.ASCII            VCの例参照

あたりが参考になるかと。

C#

// 文字列中の任意の位置の文字コードを取得 // charをintへ暗黙キャストする方法 string str = "hello"; int code = str[0]; // 先頭の1文字のコードを取得 MessageBox.Show( code.ToString() ); // 文字コードを取得 // これもchar文字をintへ暗黙キャスト code = 'a'; MessageBox.Show( code.ToString() ); // System.Text.Encoding.GetEncodin を使った方法 // GetEncodingには色んな使い方がありますが // 文字列を一気にエンコードして、結果を配列で取得する例です↓ byte[] b = System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes("abcde"); str = ""; foreach( byte data in b ) str = str + string.Format("{0} ", data); MessageBox.Show( str );

VB.NET

'VBであればAscが便利です Dim code As Integer code = Asc("a") MessageBox.Show(code.ToString()) 'System.Text.Encoding.GetEncodin を使った方法 'GetEncodingには色んな使い方がありますが '文字列を一気にエンコードして、結果を配列で取得する例です↓ Dim b(5) As Byte b = System.Text.Encoding.GetEncoding("Shift_JIS").GetBytes("abcde") Dim i As Byte Dim str As String For Each i In b str = str + String.Format("{0} ", i) Next MessageBox.Show(str)

VC.NET

// 文字列中の任意の位置の文字コードを取得 //char p[] = { 'a', 'b', 'c' }; こっちでもOK。使いやすいほうでどうぞ。 char *p = "abc"; MessageBox::Show( String::Format("{0}",p[0].ToString()) ); // こんな方法もあります。 // 文字列を一気にエンコードして、結果を配列で取得する例です↓ System::Text::Encoding *ascii = System::Text::Encoding::ASCII; Byte b[] = ascii->GetBytes("abc"); String *str = ""; for ( int i = 0; i < b->Length; i ++ ) str = str->Concat( str, String::Format("{0} ", b[i].ToString()) ); MessageBox::Show( str );




Copyright © 2008.07 - shougo suzaki