问题描述
我正在尝试使用浮点值实现_mm_and_ps
。 documentation表示此函数是4个单精度浮点数的按位计算,但是我不确定如何计算2个浮点数的按位计算。基本上我想实现以下
vector<float> bitwise_and(vector<float>a,vector<float> b){
assert(a.size()==4);
assert(b.size()==4);
vector<float> res(4);
for(int i=0;i<4;i++)
res[i]=a[i]&b[i]; //here is the problem
return res;
}
解决方法
您可以通过char*
指针访问数据的每个字节。
vector<float> bitwise_and(vector<float>a,vector<float> b){
assert(a.size()==4);
assert(b.size()==4);
vector<float> res(4);
for(int i=0;i<4;i++)
for (size_t j = 0; j < sizeof(float); j++)
reinterpret_cast<char*>(&res[i])[j]=
reinterpret_cast<char*>(&a[i])[j]&
reinterpret_cast<char*>(&b[i])[j];
return res;
}
另一种方法是使用union
以float
的身份访问int
的内存(假设int
的大小与float
相同)
vector<float> bitwise_and(vector<float>a,vector<float> b){
assert(a.size()==4);
assert(b.size()==4);
assert(sizeof(float)==sizeof(int));
vector<float> res(4);
union hoge { float fl; int in; };
for(int i=0;i<4;i++) {
hoge res_h,a_h,b_h;
a_h.fl = a[i];
b_h.fl = b[i];
res_h.in = a_h.in & b_h.in;
res[i] = res_h.fl;
}
return res;
}