【发布时间】:2022-01-22 21:54:42
【问题描述】:
我有一些表示位掩码的整数值,例如 154 = 0b10011010,我想构造一个对应的信号 Vector<T> 实例 <0, -1, 0, -1, -1, 0, 0, -1>。
肯定有比这更有效的方法吗?
int mask = 0b10011010;// 154
// -1 = (unsigned) 0xFFFFFFFF is the "true" value
Vector<int> maskVector = new Vector<int>(
Enumerable.Range(0, Vector<int>.Count)
.Select(i => (mask & (1 << i)) > 0 ? -1 : 0)
.ToArray());
// <0, -1, 0, -1, -1, 0, 0, -1>
string maskVectorStr = string.Join("", maskVector);
注意the debugger is bugged 显示Vector<T> 值,仅显示一半组件,其余部分为零,因此我使用string.Join。
此外,在使用通用 Vector<T> 版本时我该如何做到这一点?
ConditionalSelect 的文档明确指出,掩码向量对于每个重载都有整数值,但是发送垃圾邮件 Vector<T>.Zero[0] 和 Vector<T>.One[0] 来获取它们肯定是不合适的吗? (您可以使用(-Vector<T>.One)[0] 获得-1 的T 版本)
信号向量或整数掩码向量与ConditionalSelect 方法一起用于在其他两个掩码的值之间进行选择:
//powers of two <1, 2, 4, 8, 16, 32, 64, 128>
Vector<int> ifTrueVector = new Vector<int>(Enumerable.Range(0, Vector<int>.Count).Select(i => 1 << i).ToArray());
Vector<int> ifFalseVector = Vector<int>.Zero;// or some other vector
// <0, 2, 0, 8, 16, 0, 0, 128>
Vector<int> resultVector = Vector.ConditionalSelect(maskVector, ifTrueVector, ifFalseVector);
string resultStr = string.Join("", resultVector);
// our original mask value back
int sum = Vector.Dot(resultVector, Vector<int>.One);
附注是否也有相应的解决方案来填充 2 的幂?
【问题讨论】:
-
你是如何从
0b10011010到<0, -1, 0, -1, -1, 0, 0, -1>的? -
颠倒顺序。最低有效位是第一个向量分量。
-
(请注意,您的
ConditionalSelect可以使用&,我认为?这意味着不需要ifFalseVector。See the implementation) -
我看不出你的代码有什么问题。该操作需要循环16次。
-
你能用
System.Runtime.Intrinsics.X86吗?如果是这样,有 x86 特定的有效解决方案
标签: c# vector simd intrinsics bitmask