ヘッダー
C# サンプル集
 

バイト型の配列を数値にする

2022/10/30

→ Visual Basic のサンプルに切り替える → Python のサンプルに切り替える

 

バイト型の配列 {0x87,0xd6,0x12,0x00} を int型 の 1234567 にする。(リトルエンディアン)

byte[] bins = {0x87, 0xd6, 0x12, 0x00};

int number = BitConverter.ToInt32(bins, 0);

System.Diagnostics.Debug.WriteLine(number); //1234567

Debug.WriteLineが表示される場所

メモ:1234567 は 16進数表記では 0x0012D687 です。

メモ:既定ではリトルエンディアンとして扱われます。

 

 

バイト型の配列 {0x87,0xd6,0x12,0x00,0x00,0x00,0x00,0x00} を long型 の 1234567 にする。(リトルエンディアン)

byte[] bins = {0x87, 0xd6, 0x12, 0x00, 0x00, 0x00, 0x00, 0x00};

long number = BitConverter.ToInt64(bins, 0);

System.Diagnostics.Debug.WriteLine(number); //1234567

Debug.WriteLineが表示される場所

メモ:long型の情報量は8バイトなので、long と解釈する場合 変換対象のバイト型の配列の要素は8個必要です。

メモ:123456を8バイト分の16進数で表記すると 0x000000000012D687 です。

メモ:既定ではリトルエンディアンとして扱われます。

 

 

バイト型の配列 {0x00,0x12,0xd6,0x87} を int型 の 1234567 にする。(ビッグエンディアン)

byte[] bins = {0x00, 0x12, 0xd6, 0x87};

int number = BitConverter.ToInt32(bins.Reverse().ToArray(), 0);

System.Diagnostics.Debug.WriteLine(number); //1234567

Debug.WriteLineが表示される場所

メモ:1234567 は 16進数表記では 0x0012D687 です。

 

 

バイト型の配列 {0x00,0x00,0x00,0x00,0x00,0x12,0xd6,0x87} を long型 の 1234567 にする。(ビッグエンディアン)

byte[] bins = {0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0xd6, 0x87};

long number = BitConverter.ToInt64(bins.Reverse().ToArray(), 0);

System.Diagnostics.Debug.WriteLine(number); //1234567

Debug.WriteLineが表示される場所

メモ:long型の情報量は8バイトなので、変換対象のバイト型の配列の要素は8個必要です。

メモ:123456を8バイト分の16進数で表記すると 0x000000000012D687 です。