C# で16進数表記の文字列からバイト配列に格納したり
バイト配列から16進数表記の文字列に変換する方法はない?ようですね

どうやら自前でやるしかないということで作りました
もっと手軽な方法がありそうな気もしますが...

    public byte[] HexToByte(string hex)
    {
        int j = 0;
        // 2文字ずつバイト配列に格納
        Byte[] b= new Byte[hex.Length / 2];
        try
        {
            // 2バイトずつループする
            for (int i = 0; i < hex.Length - 1; i += 2)
            {
                // 16進数表記の文字列をバイトに変換する
                b[j] = Byte.Parse(String.Concat(hex[i], hex[i + 1]), System.Globalization.NumberStyles.HexNumber);
                j++;
            }
        }
        catch {}
        // バイト配列を返す
        return b;
    }

    public string ByteToHex(byte[] b)
    {
        StringBuilder Hex = new StringBuilder(b.Length * 2);
        foreach (byte bit in b)
        {
            // 文字列表記の16進数にバイトを変換する
            hex.Append(bit.ToString("x"));
        }
        return hex.ToString();
    }

Currently rated 2.0 by 1 people

  • Currently 2/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

 米田です。



@IT > Insider.NET > .NET TIPS > 2進数文字列と16進数文字列を相互に変換するには?

www.atmarkit.co.jp/.../convhex.html" rel="nofollow">www.atmarkit.co.jp/.../convhex.html">www.atmarkit.co.jp/.../convhex.html" rel="nofollow">www.atmarkit.co.jp/.../convhex.html

が参考になりそうです。

------------------

 16進数文字列から数値へは、ConvertクラスのToInt32メソッドを使用して変換できる。

int v2 = Convert.ToInt32("ff", 16);

------------------

 Convertクラスの基数指定が紹介されていました。


          

チャム&レオ says:

あぁ日本語の記事があったんですね(^^;;



でもできるのはUInt64まででしょうか?

Convert.ToString(byte[] b, int toBase)

Convert.ToByteArray(string hex, int fromBase)

みたいなメソッドがあったらありがたいですねぇ
          

Comments are closed