---
title: "HLSL modulo and signed remainder"
url: https://recursiveai.org/oneshader/cookbook/hlsl-modulo/
description: "Use HLSL modulo for signed integer remainders, fmod for floats, and a nonnegative wrap for indices. Run the example on Vulkan from C#."
version: "1.7.1"
---

# HLSL modulo and signed remainder

**OneShader** is a free, open-source HLSL compiler library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneShader.Build) · [GitHub](https://github.com/recursive-ai-oss/oneshader-csharp) · [Docs](https://recursiveai.org/oneshader/docs/) · [Download example (.zip)](https://recursiveai.org/oneshader/cookbook/hlsl-modulo/hlsl-modulo.zip)

Some GPU drivers return the wrong sign for a negative operand. Use `%` on the magnitude, then restore the sign.

```shell
dotnet add package RecursiveAI.OneShader.Build
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```hlsl
int SignedRem(int x, int d) {
    int r = int(uint(abs(x)) % uint(d));
    return x < 0 ? -r : r;
}
```

Unzip [the example](https://recursiveai.org/oneshader/cookbook/hlsl-modulo/hlsl-modulo.zip), then `dotnet run`.

The C# runner prints `Signed remainder: -2` for `SignedRem(-5, 3)`. Use a positive divisor and don’t pass `INT_MIN` as the dividend.

**Input: `Modulo.hlsl`.** The zip puts this file beside `Program.cs`. OneShader.Build compiles it and generates `Example.Shaders.Modulo` from the project’s `RootNamespace` (`Example`) and the file name. Put this entry point and buffer below `SignedRem` in the same file:

```hlsl
RWStructuredBuffer<int> Data : register(u0);

[shader("compute")]
[numthreads(1, 1, 1)]
void CSMain()
{
    int value = Data[0];
    int divisor = Data[1];
    int r = SignedRem(value, divisor);
    Data[2] = r;
    // fmod(-5.5, 3.0), stored as raw bits.
    Data[3] = asint(fmod(float(value) - 0.5, float(divisor)));
    Data[4] = r < 0 ? r + divisor : r;
}
```

## The full program

The example C# program runs the shader on Vulkan 1.3. Only the example runner uses the system Vulkan loader and driver; the compiler has no native dependencies. If you’re assembling the project yourself, add the Vulkan package too:

```shell
dotnet add package RecursiveAI.OneGpu.Vulkan
```

C# supplies `-5` and `3` through a storage buffer. The Vulkan dispatch runs one thread and reads back the three results. The floating-point test uses `-5.5` and `3.0`; the shader and C# reinterpret its result as bits to share the integer buffer without rounding it to an integer.

```csharp
using System.Globalization;
using Example.Shaders;
using RecursiveAI.OneGpu;
using RecursiveAI.OneGpu.Vulkan;

CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
using var device = VulkanGpu.CreateDevice();
using var data = device.CreateBuffer<int>(5);
data.Write([-5, 3, 0, 0, 0]);

using var kernel = device.CreateComputeKernel(
    new ShaderSource(ShaderStage.Compute, Modulo.CSMain.EntryPoint)
    { SpirV = Modulo.CSMain.SpirV, Layout = Modulo.CSMain.Layout });
using var group = kernel.CreateBindGroup(device, 0,
    [BindGroupEntry.ForBuffer(0, data.Buffer)]);
var commands = device.BeginCommands();
var pass = commands.BeginComputePass();
pass.SetPipeline(kernel.Pipeline);
pass.SetBindGroup(0, group);
pass.Dispatch(1, 1, 1);
pass.EndPass();
device.Submit(commands);

var values = new int[5];
await data.ReadAsync(values);
Console.WriteLine($"Signed remainder: {values[2]}");
Console.WriteLine($"fmod: {BitConverter.Int32BitsToSingle(values[3])}");
Console.WriteLine($"Wrapped index: {values[4]}");
```

**NVIDIA GeForce RTX 4070:**

```text
Signed remainder: -2
fmod: -2.5
Wrapped index: 1
```

**llvmpipe (Mesa lavapipe):**

```text
Signed remainder: -2
fmod: -2.5
Wrapped index: 1
```

On Linux with Mesa’s lavapipe installed, select it by setting `VK_ICD_FILENAMES` to your lavapipe manifest, for example `/usr/share/vulkan/icd.d/lvp_icd.json`, before running `dotnet run`.

`VulkanGpu.CreateDevice()` throws `GpuUnsupportedException` if it can’t find a Vulkan loader or a suitable adapter.

## Variations

**Floating-point remainder.** Use [`fmod`](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-fmod) when the fractional part matters:

```hlsl
float remainder = fmod(-5.5, 3.0); // -2.5
```

**Nonnegative index.** If negative inputs should wrap into a ring with three slots, add the period only when the signed remainder is negative:

```hlsl
int r = SignedRem(-5, 3);
int index = r < 0 ? r + 3 : r; // 1
```

## Related recipes

- [Compile an HLSL compute shader in C#](https://recursiveai.org/oneshader/cookbook/hlsl-compute-shader/)
- [Run a compute shader in C#](https://recursiveai.org/onegpu/cookbook/run-a-compute-shader-in-csharp/)

---

## The short answer

HLSL’s `%` operator gives a remainder. For signed integers with a positive divisor, the helper above takes the remainder on unsigned magnitudes and restores the dividend’s sign. Use `fmod` for fractional remainders. For a wrapped index, convert a negative remainder into the interval from zero to the period minus one.

## What does the HLSL modulo operator do?

A remainder is what’s left after division into whole multiples. For `5` divided by `3`, the quotient is `1` and the remainder is `2`. For `-5` divided by `3`, truncating the quotient toward zero gives `-1`, so the signed remainder is `-2`: `-5 = (-1 × 3) + (-2)`. Microsoft’s [HLSL operator reference](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#additive-and-multiplicative-operators) only defines `%` for operands with matching signs. In the example, `%` works on unsigned values and the return expression supplies the sign separately. Pass a positive divisor and don’t call this version of the helper with `INT_MIN`: its absolute value doesn’t fit in a signed 32-bit integer.

## How do you calculate floating-point modulo in HLSL?

`fmod(x, y)` returns a remainder with the sign of `x`, with magnitude less than the magnitude of `y` for finite inputs and a nonzero divisor. That’s why `fmod(-5.5, 3.0)` gives `-2.5`, not `0.5`. Don’t cast a fractional value to `int` to get a remainder; the cast discards the fractional part before the division. See the [HLSL `fmod` reference](https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-fmod) for the definition.

## How do you get a nonnegative modulo result in HLSL?

Use a nonnegative result for an array index, a tile number, or any other position that cycles through `0` to `period - 1`. Starting from the signed remainder, adding a positive period once is enough: that remainder is already strictly greater than `-period`. With period `3`, `-5` wraps to `1`, `-1` wraps to `2`, and an exact multiple stays at `0`. This is different from taking the absolute value of the remainder: making `-2` into `2` would select the wrong slot for `-5`.
