Skip to content

Commit

Permalink
Run formatter over HexHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
Beyley committed Aug 25, 2024
1 parent 6cc711a commit ad11849
Showing 1 changed file with 13 additions and 13 deletions.
26 changes: 13 additions & 13 deletions Refresh.Common/Helpers/HexHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace Refresh.Common.Helpers;
public static class HexHelper
{
/// <summary>
/// Converts a byte array to a hex string
/// Converts a byte array to a hex string
/// </summary>
/// <param name="data">The hex bytes</param>
/// <returns>The hex string</returns>
Expand All @@ -22,44 +22,44 @@ public static string BytesToHexString(ReadOnlySpan<byte> data)

return new string(hexChars);
}

/// <summary>
/// Converts a hex string to a byte array
/// Converts a hex string to a byte array
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static byte[] HexStringToBytes(string hex) {
public static byte[] HexStringToBytes(string hex)
{
if (hex.Length % 2 != 0)
throw new FormatException("The hex string is invalid as it contains an odd number of bytes.");

// Two hex digits per byte
byte[] arr = new byte[hex.Length / 2];

for (int i = 0; i < arr.Length; ++i)
{
// The bitmasks may seem redundant, but from my testing it consistently improves perf by ~10%,
// probably because the compiler/JIT knows it can omit range checks in the byte -> int cast
arr[i] = (byte)(((GetHexVal(hex[i * 2]) << 4) & 0xF0) + (GetHexVal(hex[i * 2 + 1]) & 0x0F));
}


return arr;
}

/// <summary>
/// Gets the 4 bit value of the single hex digit
/// Gets the 4 bit value of the single hex digit
/// </summary>
/// <param name="hex">The hex digit</param>
/// <returns>The 4 bit value of the digit</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining | MethodImplOptions.AggressiveOptimization)]
private static int GetHexVal(char hex) {
private static int GetHexVal(char hex)
{
int val = hex;
return val - (val < 58 ? 48 : 87);
}

/// <summary>
/// Gets the hex digit for a 4-bit value
/// Gets the hex digit for a 4-bit value
/// </summary>
/// <param name="value">The 4 bit value</param>
/// <returns>The hex digit</returns>
Expand Down

0 comments on commit ad11849

Please sign in to comment.