将整数结构转换为位掩码

Converting a struct of integers into a bitmask

是否可以(如果可以,如何)将整数结构转换为位掩码。每个整数一位(如果 int 为 0,则为 0,否则为 1)。例如

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

您可以明确地这样做:

char mask(const Int_List_t& vals)
{
    return (vals.int1 ? 0x8 : 0x0) |
           (vals.int2 ? 0x4 : 0x0) |
           (vals.int3 ? 0x2 : 0x0) |
           (vals.int4 ? 0x1 : 0x0);
}

如果你传入一个数组而不是一个结构,你可以写一个循环:

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;
}

如果您愿意完全绕过任何类型安全,您甚至可以通过将对象重新解释为指针来实现上述功能,尽管我不一定会推荐它:

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;
}