c++ - 如何对结构进行位操作?

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

我有一个位域结构,我想在其上使用掩码执行按位运算。 我想知道最简单和最有效的方法来做到这一点。 我曾尝试使用我的转换运算符(这似乎是对两个结构执行 & 操作的一种低效方式)但我收到错误 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));
};

这是否是我们所能达到的最高效的?它涉及三个额外的指针,而我真正需要的只是转换为 long。

最佳答案

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

除此之外:
- 您应该将 operator char() { 更改为 operator char() const { - 这正是编译器提示的地方:)
- 不应该有 byte mins: 3 而不是 unsigned mins: 3 这实际上意味着“unsigned int”所以无论如何都使用 4 个字节

关于c++ - 如何对结构进行位操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11539300/

相关文章:

c++ - 静态成员声明 c++11

c++ - 将多个基础结构组合成自定义类型

c++ - 使用 c 中结构的 malloc 对内存块进行索引

将 "if between"与按位运算符而不是逻辑运算符进行比较

java - 写入图像位掩码

c++ - for循环中使用的位操作

c++ - 使用 VideoCapture 读取目录中的图像不起作用

javascript - Crypto++ 低级 AES API(a la SJCL)

c++ - boost 函数映射到字符串

c# - 结构总是堆栈分配还是有时堆分配?