Table of Contents

Read three-byte integers

Intermediate · C#. A 24-bit integer occupies three bytes and has alignment 1, including inside aligned structs. Explicit suffixes select byte order.

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 -- integers-24

The runner checks seven bytes, unsigned maximum 16777215, signed -2, and an atomic overflow rejection. Success includes PASS integers-24.

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()
    {
        Integers24();
        Console.WriteLine("PASS integers-24");
    }

    private static void Integers24()
    {
        var layout = new CStruct("struct root { uint24< size; int24< delta; uint8 tail; };", aligned: true);
        byte[] bytes = layout.Serialize("root", new Dictionary<string, object?> { ["size"] = 16777215U, ["delta"] = -2, ["tail"] = 99 });
        SequenceEqual([255, 255, 255, 254, 255, 255, 99], bytes);
        Equal(7, layout.GetStructSizeInBytes("root"));
        Equal(-2, layout.ReadValue<int>(bytes.AsSpan(), "root.delta"));
        using var stream = new MemoryStream(bytes);
        Equal(3L, layout.ResolveAddress(stream, "root.delta"));
        Throws<CStructWriteException>(() => layout.Update(stream, "root.size", 16777216U));
        SequenceEqual(bytes, stream.ToArray());
    }

    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)}.");
        }
    }

    private static void Throws<TException>(Action action)
        where TException : Exception
    {
        try
        {
            action();
        }
        catch (TException)
        {
            return;
        }

        throw new InvalidOperationException($"Expected {typeof(TException).Name}.");
    }
}

Try it and diagnose mistakes

Change delta to -1 and predict its three bytes.

Answer: The signed field becomes FF FF FF; the following byte stays at offset 6. 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.