for WPF developers
Home Profile Tips 全記事一覧

string 文字列を文字コードに変換する

(2016/12/02 20:58:05 created.)

基本データ型から byte[] に変換するときは GetBytes() メソッドを使います。

Program.cs
  1. namespace Tips_BitConverter
  2. {
  3.     using System;
  4.     using System.Linq;
  5.     class Program
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             byte[] bytes;
  10.             int int32;
  11.  
  12.             // bytes = { 0x78, 0x56, 0x34, 0x12 }
  13.             int32 = 0x12345678;
  14.             bytes = BitConverter.GetBytes(int32);
  15.             PrintByteArray(bytes);
  16.  
  17.             // bytes = { 0x12, 0x34, 0x56, 0x78 }
  18.             int32 = 0x78563412;
  19.             bytes = BitConverter.GetBytes(int32);
  20.             PrintByteArray(bytes);
  21.  
  22.             Console.ReadKey();
  23.         }
  24.  
  25.         static void PrintByteArray(byte[] bytes)
  26.         {
  27.             var str = bytes.Select(x => "0x" + x.ToString("X2"));
  28.             Console.WriteLine("Bytes = {{ {0} }}", string.Join(", ", str));
  29.         }
  30.     }
  31. }
  32.  

実行結果を見てもわかるように、リトルエンディアンの場合は byte[] に変換した後の要素の順番が入れ替わります。

GetBytes() メソッドの入力引数は short や long など他のデータ型も指定することができるので、とにかく byte[] に変換したいときはこのメソッドを使うことができます。