将整数结构转换为位掩码

时间:2015-01-20 16:23:15

标签: c++ struct 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

1 个答案:

答案 0 :(得分:2)

您可以明确地执行此操作:

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