Skip to content

Commit 31f906c

Browse files
committed
Added HasZeroByte APIs
1 parent f4b87e1 commit 31f906c

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
@@ -103,6 +103,37 @@ public static bool HasLookupFlag(uint table, int x, int min = 0)
103103
return valid;
104104
}
105105

106+
/// <summary>
107+
/// Checks whether the given value has any bytes that are set to 0.
108+
/// That is, given a <see cref="uint"/> value, which has a total of 4 bytes,
109+
/// it checks whether any of those have all the bits set to 0.
110+
/// </summary>
111+
/// <param name="value">The input value to check.</param>
112+
/// <returns>Whether <paramref name="value"/> has any bytes set to 0.</returns>
113+
/// <remarks>
114+
/// This method contains no branches.
115+
/// For more info, see <see href="https://graphics.stanford.edu/~seander/bithacks.html"/>.
116+
/// </remarks>
117+
[Pure]
118+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
119+
public static bool HasZeroByte(uint value)
120+
{
121+
return ((value - 0x0101_0101u) & ~value & 0x8080_8080u) != 0;
122+
}
123+
124+
/// <summary>
125+
/// Checks whether the given value has any bytes that are set to 0.
126+
/// This method mirrors <see cref="HasZeroByte(uint)"/>, but with <see cref="ulong"/> values.
127+
/// </summary>
128+
/// <param name="value">The input value to check.</param>
129+
/// <returns>Whether <paramref name="value"/> has any bytes set to 0.</returns>
130+
[Pure]
131+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
132+
public static bool HasZeroByte(ulong value)
133+
{
134+
return ((value - 0x0101_0101_0101_0101ul) & ~value & 0x8080_8080_8080_8080ul) != 0;
135+
}
136+
106137
/// <summary>
107138
/// Sets a bit to a specified value.
108139
/// </summary>

0 commit comments

Comments
 (0)