// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Microsoft.Toolkit.Extensions { /// /// Helpers for working with value types. /// public static class ValueTypeExtensions { /// /// Gets the table of hex characters (doesn't allocate, maps to .text section, see ) /// private static ReadOnlySpan HexCharactersTable => new[] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F' }; /// /// Returns a hexadecimal representation of a given value, left-padded and ordered as big-endian. /// /// The input type to format to . /// The input value to format to . /// /// The hexadecimal representation of (with the '0x' prefix), left-padded to byte boundaries and ordered as big-endian. /// /// /// As a byte (8 bits) is represented by two hexadecimal digits (each representing a group of 4 bytes), each /// representation will always contain an even number of digits. For instance: /// /// Console.WriteLine(1.ToHexString()); // "0x01" /// Console.WriteLine(((byte)255).ToHexString()); // "0xFF" /// Console.WriteLine((-1).ToHexString()); // "0xFFFFFFFF" /// /// [Pure] [MethodImpl(MethodImplOptions.NoInlining)] public static unsafe string ToHexString(this T value) where T : unmanaged { int sizeOfT = Unsafe.SizeOf(), bufferSize = (2 * sizeOfT) + 2; char* p = stackalloc char[bufferSize]; p[0] = '0'; p[1] = 'x'; ref byte r0 = ref Unsafe.As(ref value); ref byte rh = ref MemoryMarshal.GetReference(HexCharactersTable); for (int i = 0, j = bufferSize - 2; i < sizeOfT; i++, j -= 2) { byte b = Unsafe.Add(ref r0, i); int low = b & 0x0F, high = (b & 0xF0) >> 4; p[j + 1] = (char)Unsafe.Add(ref rh, low); p[j] = (char)Unsafe.Add(ref rh, high); } return new string(p, 0, bufferSize); } } }