スキップしてメイン コンテンツに移動

投稿

ラベル(byte order)が付いた投稿を表示しています

C#でbyte orderを反転する方法

UDPパケットの受信時に受信したデータのbyte orderを反転する必要がある場合があります。そんな場合に使えるbyte orderを反転するC#のコードの紹介です。 処理の流れは下記になります。 BitConverter.GetBytesメソッドを使って、値のbyte配列表現を取得。 Array.Reverseメソッドでbyte配列の順番を反転する。 BitConverter.ToXXXメソッドで元の値の型に戻す。 ushort, uint, int, ulong, float, doubleなどの型についてコードを示します。 public static void ReverseBytes ( this ref ushort value ) { var source = BitConverter . GetBytes ( value ) ; Array . Reverse ( source ) ; value = BitConverter . ToUInt16 ( source , 0 ) ; } public static void ReverseBytes ( this ref uint value ) { var source = BitConverter . GetBytes ( value ) ; Array . Reverse ( source ) ; value = BitConverter . ToUInt32 ( source , 0 ) ; } public static void ReverseBytes ( this ref int value ) { var source = BitConverter . GetBytes ( value ) ; Array . Reverse ( source ) ; value = BitConverter . ToInt32 ( source , 0 ) ; } public static void ReverseBytes ( this ref ulong value ) { v