Byte alignment in C# [closed]

3 days ago 5
ARTICLE AD BOX

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; }
Read Entire Article