byte[] から int などのデータ型に変換する
(2016/12/02 15:55:58 created.)
(2016/12/02 20:27:58 modified.)
byte[] から基本データ型に変換するときは、例えば int 型の場合は ToInt32() メソッド、long 型の場合は ToInt64() メソッドを使います。
Program.cs
namespace Tips_BitConverter
{
using System;
class Program
{
static void Main(string[] args)
{
byte[] bytes;
int int32;
// 0x78563412
bytes = new byte[] { 0x12, 0x34, 0x56, 0x78 };
int32 = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int32 = 0x{0}", int32.ToString("X8"));
// 0x12345678
bytes = new byte[] { 0x78, 0x56, 0x34, 0x12 };
int32 = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("int32 = 0x{0}", int32.ToString("X8"));
Console.ReadKey();
}
}
}
実行結果から見てもわかるように、リトルエンディアンの場合は元となる byte[] の要素の順番とは逆の順番になります。他にも ToBoolean()、ToChar() などのメソッドも用意されています。
Tweet