Table of Contents

Explain padding in an aligned header

Intermediate · C#. Two padding bytes follow kind. A four-byte length begins at an offset divisible by four.

Run this example

Prerequisites: the repository's .NET 10 SDK and a checkout of this source. Run from the repository root:

dotnet run --project docs/examples/CStructSharp.Docs.Examples.csproj -c Release -- aligned-header

The runner checks length 6 at offset 4; eight-byte round trip. Success includes PASS aligned-header.

Try the related browser lesson.

Complete program

The layout, options, input bytes, helper methods, and required types are all included. To adapt it outside the repository, create a .NET 10 console project, add CStructSharp, and replace Program.cs with this complete file. These examples follow the source version; use a matching package when testing a release.

Download the complete C# source.

// Generated from executable documentation examples. Edit the source region, then regenerate.
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Buffers;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using CStructSharp;
using CStructSharp.Codecs;
using CStructSharp.Diagnostics;
using CStructSharp.Introspection;
using CStructSharp.Values;

internal static partial class Program
{
    public static void Main()
    {
        AlignedHeader();
        Console.WriteLine("PASS aligned-header");
    }

    private static void AlignedHeader()
    {
        var layout = new CStruct("struct header { uint16 kind; uint32 length; };", aligned: true);
        byte[] bytes = [2, 0, 0, 0, 6, 0, 0, 0];
        Equal(6U, (uint)layout.ReadValue(bytes.AsSpan(), "header.length")!);
        using var stream = new MemoryStream(bytes);
        Equal(4L, layout.ResolveAddress(stream, "header.length"));
        SequenceEqual(bytes, layout.Serialize("header", layout.Parse(bytes.AsSpan(), "header")));
    }

    private static void Equal<T>(T expected, T actual)
    {
        if (!EqualityComparer<T>.Default.Equals(expected, actual))
        {
            throw new InvalidOperationException($"Expected '{expected}', received '{actual}'.");
        }
    }

    private static void SequenceEqual(byte[] expected, byte[] actual)
    {
        if (!expected.AsSpan().SequenceEqual(actual))
        {
            throw new InvalidOperationException(
                $"Expected {Convert.ToHexString(expected)}, received {Convert.ToHexString(actual)}.");
        }
    }
}

Try it and diagnose mistakes

Predict the position with aligned set to false.

Answer: Packed length starts at 2, so the packed input must omit the two padding bytes. The program contains assertions for its original inputs. When changing an input intentionally, update the expected assertion too; an unchanged assertion is not evidence that the new value is wrong.

Continue with the related guide or choose another recipe.