【C#】Byte / Byte[] (Byteの配列)

エンディアンの対応

 * 以下の公式サイトに記載されてた
https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/types/how-to-convert-a-byte-array-to-an-int
 * 「BitConverter.IsLittleEndian」と「Array.Reverse()」で対応

if (BitConverter.IsLittleEndian)
{
  Array.Reverse(bytes);
}

■ 文字列 <=> バイナリデータ(byte[])の相互変換

文字列 => バイナリデータ

 * 以下のメソッドを使用する
  + Encoding.ASCII.GetBytes()
   => 半角英数字のみ(日本語未対応)
  + Byte.TryParse()
https://docs.microsoft.com/ja-jp/dotnet/api/system.byte.tryparse?view=netstandard-2.1

バイナリデータ => 文字列

 * 以下のメソッドを使用する
   + Encoding.ASCII.GetString()
   + BitConverter.ToString()

Byte[] = System.Text.Encoding.ASCII.GetBytes("Test");
http://cammy.co.jp/technical/2017/05/19/c-%E3%83%90%E3%82%A4%E3%83%88%E5%88%97byte%E3%82%92%E5%A4%89%E6%8F%9B%E3%81%99%E3%82%8B/

■ プリミティブ型 <=> バイナリデータ(byte)の相互変換

https://docs.microsoft.com/ja-jp/dotnet/csharp/programming-guide/types/how-to-convert-a-byte-array-to-an-int

数字 => Byte

 * BitConverter.GetBytes(【数字】)で変換

double value = -8.7033552055E+06;

// var 【Byte配列】 = BitConverter.GetBytes(【数字】)
var byteValues = BitConverter.GetBytes(value);

Byte[] => 数字

 * BitConverter.To[数字の型(例:Int32)](【Byte配列】)で変換

private void button2_Click(object sender, EventArgs e)
{
  byte[] bytes = { 0x00, 0x00, 0x00, 0x0C };

  // If the system architecture is little-endian (that is, little end first),
  // reverse the byte array.
  // コンピューター アーキテクチャがリトル エンディアンである場合
  //  (つまり、下位バイトから先に格納する場合) は、配列を反転
  if (BitConverter.IsLittleEndian)
  {
    Array.Reverse(bytes);
  }
  int value = BitConverter.ToInt32(bytes, 0);
  this.textBox1.Text = string.Format("int: {0}", value);
}

■ Bitmap <=> バイナリデータ(byte[])の相互変換

 * 以下の関連記事を参照のこと
C#】Bitmap / BitmapData
https://blogs.yahoo.co.jp/dk521123/38086057.html