1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C#でバイト配列を扱う

Last updated at Posted at 2025-08-07

1. はじめに

C# で バイト配列を扱う機会があったのでやってみた自分用メモ。

以下の記事に感謝します。

2.コード

型のサイズだとかエンディアンだとか説明しだすとキリがないのでばっさり省略。

sample.cs
// バージョンによってはバイト列の比較、連結にはLinqが必要
using System.Linq;

namespace Test001
{
    internal class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8};

            // 4バイトだけ抜き出す例
            byte[] dest0 = new byte[4];
            byte[] dest1 = new byte[4];

            // 途中から指定長抜き出す
            // 期待値 3, 4, 5, 6
            Buffer.BlockCopy(data, 3, dest0, 0, 4);

            // バイト列 -> DWORD
            // 0x06050403
            uint dwordValue = BitConverter.ToUInt32(dest0, 0); 

            // DWORD->バイト列
            dest1 = BitConverter.GetBytes(dwordValue);

            // 連結(Linq)
            // 期待値 3,4,5,6,3,4,5,6
            byte[] dest2 = dest0.Concat(dest1).ToArray();
            
            // バイト列の比較(Linq)
            if(dest0.SequenceEqual(dest1))
            {
                // 期待値
                Console.WriteLine("一致");
            }
            else
            {
                Console.WriteLine("不一致");
            }
        }
    }
}

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?