for WPF developers
Home Profile Tips 全記事一覧

byte[] から int などのデータ型に変換する

(2016/12/02 15:55:58 created.)

(2016/12/02 20:27:58 modified.)

byte[] から基本データ型に変換するときは、例えば int 型の場合は ToInt32() メソッド、long 型の場合は ToInt64() メソッドを使います。

Program.cs
  1. namespace Tips_BitConverter
  2. {
  3.     using System;
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.             byte[] bytes;
  9.             int int32;
  10.  
  11.             // 0x78563412
  12.             bytes = new byte[] { 0x12, 0x34, 0x56, 0x78 };
  13.             int32 = BitConverter.ToInt32(bytes, 0);
  14.             Console.WriteLine("int32 = 0x{0}", int32.ToString("X8"));
  15.  
  16.             // 0x12345678
  17.             bytes = new byte[] { 0x78, 0x56, 0x34, 0x12 };
  18.             int32 = BitConverter.ToInt32(bytes, 0);
  19.             Console.WriteLine("int32 = 0x{0}", int32.ToString("X8"));
  20.  
  21.             Console.ReadKey();
  22.         }
  23.     }
  24. }

実行結果から見てもわかるように、リトルエンディアンの場合は元となる byte[] の要素の順番とは逆の順番になります。他にも ToBoolean()、ToChar() などのメソッドも用意されています。