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

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

UDPパケットの受信時に受信したデータのbyte orderを反転する必要がある場合があります。そんな場合に使えるbyte orderを反転するC#のコードの紹介です。

処理の流れは下記になります。

  1. BitConverter.GetBytesメソッドを使って、値のbyte配列表現を取得。
  2. Array.Reverseメソッドでbyte配列の順番を反転する。
  3. 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)
{
    var source = BitConverter.GetBytes(value);
    Array.Reverse(source);
    value = BitConverter.ToUInt64(source, 0);
}

public static void ReverseBytes(this ref float value)
{
    var source = BitConverter.GetBytes(value);
    Array.Reverse(source);
    value = BitConverter.ToSingle(source, 0);
}

public static void ReverseBytes(this ref double value)
{
    var source = BitConverter.GetBytes(value);
    Array.Reverse(source);
    value = BitConverter.ToDouble(source, 0);
}

上記のサンプルコードでは拡張メソッドを使ってvalue.ReverseBytes() という呼び出し方で反転するようにしていますが、単純に反転後の値を返すメソッドの方が使いやすい場合もあると思います。その場合は下記のようなコードになります。

public static ushort ReverseBytes(ushort value)  
{  
    var source = BitConverter.GetBytes(value);  
    Array.Reverse(source);  
    return BitConverter.ToUInt16(source, 0);  
}

コメント