Skip to content

Commit 4ebe64a

Browse files
committed
Added HasByteEqualTo APIs
1 parent 1110a83 commit 4ebe64a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Microsoft.Toolkit.HighPerformance/Helpers/BitHelper.cs

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,37 @@ public static bool HasZeroByte(ulong value)
134134
return ((value - 0x0101_0101_0101_0101ul) & ~value & 0x8080_8080_8080_8080ul) != 0;
135135
}
136136

137+
/// <summary>
138+
/// Checks whether a byte in the input <see cref="uint"/> value matches a target value.
139+
/// </summary>
140+
/// <param name="value">The input value to check.</param>
141+
/// <param name="target">The target byte to look for.</param>
142+
/// <returns>Whether <paramref name="value"/> has any bytes set to <paramref name="target"/>.</returns>
143+
/// <remarks>
144+
/// This method contains no branches.
145+
/// For more info, see <see href="https://graphics.stanford.edu/~seander/bithacks.html"/>.
146+
/// </remarks>
147+
[Pure]
148+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
149+
public static bool HasByteEqualTo(uint value, byte target)
150+
{
151+
return HasZeroByte(value ^ (0x0101_0101u * target));
152+
}
153+
154+
/// <summary>
155+
/// Checks whether a byte in the input <see cref="uint"/> value matches a target value.
156+
/// This method mirrors <see cref="HasByteEqualTo(uint,byte)"/>, but with <see cref="ulong"/> values.
157+
/// </summary>
158+
/// <param name="value">The input value to check.</param>
159+
/// <param name="target">The target byte to look for.</param>
160+
/// <returns>Whether <paramref name="value"/> has any bytes set to <paramref name="target"/>.</returns>
161+
[Pure]
162+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
163+
public static bool HasByteEqualTo(ulong value, byte target)
164+
{
165+
return HasZeroByte(value ^ (0x0101_0101_0101_0101u * target));
166+
}
167+
137168
/// <summary>
138169
/// Sets a bit to a specified value.
139170
/// </summary>

0 commit comments

Comments
 (0)