Byte alignment in C#

Ken Netherland 21 Reputation points
2026-01-31T23:36:49.72+00:00

I found the following code online, although I had to refactor to support .NET 4. So nint was converted to IntPtr.

The code seems to work fine with an alignment of 8, 16, and 32, but breaks down at 64. Any ideas?

    public static IntPtr ByteAlign(IntPtr unalignedPtr, int alignment)

    {

        // Ensure alignment is a power of two for this method to work correctly

        if ((alignment & (alignment - 1)) != 0)

        {

            throw new ArgumentException("Alignment must be a power of 2.", nameof(alignment));

        }

        var address = (ulong)unalignedPtr;

        var alignmentOffsetAddress = (address + (ulong)(alignment - 1));    // add alignment to address (next alignment row in memory)

        var mask = ~((ulong)(alignment - 1));                               // mask off the significant bits with alignment to align to the left side of the alignment row

        var alignedAddress = alignmentOffsetAddress & mask;

        return (IntPtr)alignedAddress;

    }
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 82,606 Reputation points Volunteer Moderator
    2026-02-01T17:22:52.1966667+00:00

    Check that the app is built as 64 bit for IntPtr to support 64 bit address.

    0 comments No comments

  2. Jack Dang (WICLOUD CORPORATION) 10,985 Reputation points Microsoft External Staff Moderator
    2026-02-03T04:46:32.51+00:00

    Hi @Ken Netherland ,

    Thanks for reaching out.

    The issue at 64 isn’t a bug in the math, it’s an assumption problem. In managed .NET (especially .NET Framework 4.x), memory addresses for objects aren’t guaranteed to be 64-byte aligned. The CLR and GC usually only ensure smaller alignments (like 8 or 16 bytes), and forcing 64-byte alignment can point to memory you don’t fully control or that the GC might move.

    Also, make sure your app is built as 64-bit so IntPtr can hold large addresses; but even then, this doesn’t guarantee 64-byte alignment for managed objects.

    In short:

    • The math works.
    • .NET doesn’t guarantee 64-byte alignment.
    • Behavior at 64 bytes can be unpredictable.

    If you truly need 64-byte alignment:

    • Allocate unmanaged memory explicitly.
    • Or use native code where alignment can be enforced.
    • Avoid assuming large alignments for managed objects.

    Hope this helps! If my answer was helpful - kindly follow the instructions here so others with the same problem can benefit as well.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.