[英]Converting a struct of integers into a bitmask
Is it possible (if so, how) to convert a struct of integers into a bitmask. 是否可以(如果可以,如何)将整数结构转换为位掩码。 One bit for each integer (0 if the int is 0, otherwise 1). 每个整数一位(如果int为0,则为0,否则为1)。 For example 例如
struct Int_List_t
{
uint64_t int1;
uint64_t int2;
uint64_t int3;
uint64_t int4;
} int_list={10,0,5,0};
char int_mask = somefunction(int_list);
//Would contain 1010
||||
|||+-- int4 is 0
||+--- int3 is not 0
|+---- int2 is 0
+----- int1 is not 0
You could just do it explicitly: 您可以明确地做到这一点:
char mask(const Int_List_t& vals)
{
return (vals.int1 ? 0x8 : 0x0) |
(vals.int2 ? 0x4 : 0x0) |
(vals.int3 ? 0x2 : 0x0) |
(vals.int4 ? 0x1 : 0x0);
}
If you passed in an array instead of a struct, you could write a loop: 如果传入数组而不是结构,则可以编写循环:
template <size_t N>
uint64_t mask(uint64_t (&vals)[N])
{
uint64_t result = 0;
uint64_t mask = 1 << (N - 1);
for (size_t i = 0; i < N; ++i, mask >>= 1) {
result |= (vals[i] ? mask : 0);
}
return result;
}
If you're open to completely bypassing any type safety whatsoever, you could even implement the above by just reinterpreting your object to be a pointer, although I wouldn't necessarily recommend it: 如果您愿意完全绕过任何类型安全,甚至可以通过将对象重新解释为指针来实现上述目的,尽管我不一定会推荐它:
template <typename T>
uint64_t mask(const T& obj)
{
const uint64_t* p = reinterpret_cast<const uint64_t*>(&obj);
const uint64_t N = sizeof(T)/8;
uint64_t result = 0;
uint64_t mask = 1 << (N - 1);
for (size_t i = 0; i < N; ++i, ++p, mask >>= 1) {
result |= (*p ? mask : 0);
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.