C# – 16進数文字列とbyte型配列のバイトオーダ反転 (エンディアン変換)

概要

  • 16進数表記の文字列のバイトオーダーを反転 (エンディアンを変換)
  • バイト型の配列のバイトオーダー反転 (エンディアンを変換)

実装例

using System;

namespace BinaryEditorBase
{
    public static class BinaryEditor
    {
        /// <summary>
        /// 16進数表記文字列のバイトオーダー反転
        /// </summary>
        /// <param name="byteString">16進数表記文字列</param>
        /// <returns>反転後の16進数表記文字列</returns>
        public static string ConvertStringEndian(string byteString)
        {
            // 文字列の文字数(半角)が奇数の場合、頭に「0」を付ける
            int length = byteString.Length;
            if (length % 2 == 1)
            {
                byteString = "0" + byteString;
                length++;
            }
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            // 文字列の最後尾から2文字ずつ取得
            for (int i = length - 1; i >= 0; i -= 2)
            {
                sb.Append(byteString.Substring(i - 1, 2));
            }
            return sb.ToString();
        }

        /// <summary>
        /// バイト列のバイトオーダー反転
        /// </summary>
        /// <param name="bytes">バイト列</param>
        /// <returns>反転後のバイト列</returns>
        public static byte[] ConvertBytesEndian(byte[] bytes)
        {
            // 引数の配列と同じサイズの配列を宣言
            byte[] newBytes = new byte[bytes.Length];
            // 配列のコピーを作成
            bytes.CopyTo(newBytes, 0);
            // 反転
            Array.Reverse(newBytes);
            return newBytes;
        }

        [STAThread]
        static void Main()
        {
            try
            {
                // 16進数文字列のバイトオーダ反転
                string normalData = "0123456789ABCDEF";
                string swapData = ConvertStringEndian(normalData);
                Console.WriteLine(swapData);
                // byte型配列のバイトオーダ反転
                byte[] normalByteArray = new byte[] { 0x01, 0x02, 0x03, 0x04 };
                byte[] swapByteArray = ConvertBytesEndian(normalByteArray);
                foreach (byte b in swapByteArray)
                {
                    Console.Write(b.ToString("X2"));
                }
                Console.Write(Environment.NewLine);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            // 終了処理
            Console.Write("何かキーを押してください");
            Console.Read();
        }
    }
}

説明

(12~16行目) 文字数が奇数の場合に16進数表記的におかしな事になるので、奇数の場合は頭に「0」を付けます。

(21~24行目) 文字列の最後尾から2文字ずつ抜き出し、「StringBuilder」型の変数に格納していきます。

(33~39行目) 「Array.Reverse」メソッドは配列の反転を行うメソッドですが、引数で指定した配列を直に反転するので、 事前にコピーを作成しています。