int などのデータ型から byte[] に変換する
(2016/12/02 14:55:40 created.)
(2016/12/02 20:27:54 modified.)
基本データ型から byte[] に変換するときは GetBytes() メソッドを使います。
Program.cs
namespace Tips_BitConverter
{
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
byte[] bytes;
int int32;
// bytes = { 0x78, 0x56, 0x34, 0x12 }
int32 = 0x12345678;
bytes = BitConverter.GetBytes(int32);
PrintByteArray(bytes);
// bytes = { 0x12, 0x34, 0x56, 0x78 }
int32 = 0x78563412;
bytes = BitConverter.GetBytes(int32);
PrintByteArray(bytes);
Console.ReadKey();
}
static void PrintByteArray(byte[] bytes)
{
var str = bytes.Select(x => "0x" + x.ToString("X2"));
Console.WriteLine("Bytes = {{ {0} }}", string.Join(", ", str));
}
}
}
実行結果を見てもわかるように、リトルエンディアンの場合は byte[] に変換した後の要素の順番が入れ替わります。
GetBytes() メソッドの入力引数は short や long など他のデータ型も指定することができるので、とにかく byte[] に変換したいときはこのメソッドを使うことができます。
Tweet