Table of Contents

Preserve exact fixed-point values

Intermediate · C#. Fixed-point values are binary-scaled integers exposed as Double. Writers require an exact representable value rather than rounding silently.

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 -- fixed-point

The runner checks revision -1.5, volume 0.5, and rejected quantization of 0.1. Success includes PASS fixed-point.

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()
    {
        FixedPoint();
        Console.WriteLine("PASS fixed-point");
    }

    private static void FixedPoint()
    {
        var layout = new CStruct("struct root { fixed16_16> revision; ufixed8_8< volume; };", aligned: false);
        byte[] bytes = layout.Serialize("root", new Dictionary<string, object?> { ["revision"] = -1.5, ["volume"] = 0.5 });
        SequenceEqual([255, 254, 128, 0, 128, 0], bytes);
        Equal(-1.5, layout.ReadValue<double>(bytes.AsSpan(), "root.revision"));
        Equal(0.5, layout.ReadValue<double>(bytes.AsSpan(), "root.volume"));
        using var stream = new MemoryStream(bytes);
        Throws<CStructWriteException>(() => layout.Update(stream, "root.volume", 0.1));
        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 volume from 0.5 to 0.25.

Answer: The unsigned 8.8 raw value becomes 64, stored as 40 00 in little-endian order. 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.