4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[.NET] バイトオーダーを指定した整数・バイナリの相互変換

Last updated at Posted at 2020-09-15

Question

ある整数型をリトルエンディアン(あるいはビッグエンディアン)でbyte配列に書き込みたい。
または、byte配列に書き込まれているリトルエンディアン(あるいはビッグエンディアン)の整数型を復元したい。
どうすればいいか。
BitConverterクラスのGetBytesToInt32にはバイトオーダーを指定する方法はない。

Answer

BinaryPrimitivesクラスを使用する。

  • ReadOnlySpan<byte>から整数型(int)を復元するにはReadInt32BigEndian/ReadInt32LittleEndian
  • 整数型(int)の内容をSpan<byte>に書き出すにはWriteInt32BigEndian/WriteInt32LittleEndian

メソッドを使用する。

int i1 = 12345678;
var buffer = new byte[255];

BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(0, 4), i1);
int i2 = BinaryPrimitives.ReadInt32LittleEndian(buffer.AsSpan(0, 4));

int型だけでなく、short, ushortからlong, ulong型までサポートされている。

このクラスはSystem.Buffers.Binary名前空間にあり、.NET Core 2.1から使用できる。
.NET Frameworkを利用している場合、System.MemoryをNuGetで入手すれば使用できるようだ。
(System.Buffersではない。)

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?