如何对结构进行位操作?

时间:2012-07-18 10:28:54

标签: c++ struct bit-manipulation conversion-operator

我有一个bitfield结构,我想在其上使用掩码执行按位运算。 我想知道最简单,最有效的方法。 我已经尝试使用我的转换运算符(这似乎是对两个结构进行&操作的低效方法)但我得到错误C2440:'type cast':无法从'const test :: dtType'转换为'char'。没有可用于执行此转换的用户定义转换运算符,或者无法调用运算符

class test
{
   public:
    test() : startTime(0), endTime(5,23) {}
    ~test();

    struct dtType {
        // inline constructors with initialisation lists
        dtType() {dtType(0);}
        dtType(byte z) {dtType(z,z);}
        dtType(byte n,byte h) : mins(n), hrs(h){}

        // inline overloaded operator functions
        operator char() {return mins + hrs<<3;}; // allow casting the struct as a char

        // All I want to do is return (this & hrsMask == date & hrsMask)
        // I know that in this trivial case I can do return (hrs == date.hrs) but I have simplified it for this example.
        bool operator== (dtType date){return (char(this) & char(hrsMask)) == (char(date) & char(hrsMask));};

        // data members
        unsigned mins: 3; // 10's of mins
        unsigned hrs: 5; // 8 bits
    };
    const static dtType hrsMask; // initialised outside the declaraion, since a static is not associated with an individual object.
    dtType startTime; // initialised by test() in its initialisation list
    dtType endTime; // initialised by test() in its initialisation list
};

// Typically in a source file, but can be in the header.
const test::dtType hrsMask(0,31);

我尝试使用void指针进行按位操作。它编译,但我没有测试过。

bool test::dtType::operator== (dtType date){
    const void * longThisDT = this;
    const void * longThatDT = & date;
    const void * longMaskDT = & hrsMask;
    return (*((long *)longThisDT) &  *((long *)longMaskDT) == *((long *)longThatDT) &  *((long *)longMaskDT));
};

这和我们能得到的效率一样吗?它涉及三个额外的指针,当我真正需要的是一个长时间的演员。

2 个答案:

答案 0 :(得分:0)

首先要花时间准备工作示例,你的错误很多:
- 没有〜测试定义
- const test :: dtType hrsMask(0,31); 不正确,应该是: const test :: dtType test:hrsMask(0,31);

除此之外:
- 你应该将操作符char(){更改为操作符char()const { - 这就是编译器的唠叨:) - 不应该有字节分钟:3 而不是无符号分钟:3 这实际上意味着'unsigned int'所以无论如何使用4个字节

答案 1 :(得分:0)

this被指向并且删除了consts时,它可以正常工作:

bool operator== (dtType date) {
    return (char(*this) & char(hrsMask)) == (char(date) & char(hrsMask));};

/* ... */

static dtType hrsMask;

/* ... */

 test::dtType test::hrsMask(0,31);