Quantcast
Channel: C#タグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9509

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

$
0
0

Question

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

Answer

BinaryPrimitivesクラスを使用する。

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

メソッドを使用する。

inti1=12345678;varbuffer=newbyte[255];BinaryPrimitives.WriteInt32LittleEndian(buffer.AsSpan(0,4),i1);inti2=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ではない。)


Viewing all articles
Browse latest Browse all 9509

Trending Articles