Question

I have an old device which send thru a serial port a large array of 7-bit bytes (the most significant bit is always 0). These bytes are sent splitted in two nibbles, so a byte 0abcdefg is received as 00000abc 0000defg. So i created a DoubleByte struct to store each of them:

struct Dbyte {
    BYTE h;
    BYTE l;
};

Now, i have 2 problems:

1) what i want to do is to access each Dbyte as a normal, basic type variable, so i tried to override some operator:

struct Dbyte {
    BYTE h;
    BYTE l;
    Dbyte& operator =(const Dbyte& a) {
        l = a.l; h = a.h;
        return *this;
    }
    Dbyte& operator =(const int& i) {
        l = i&0x0F; h = i>>4 & 0x07;
        return *this;
    }
    int operator = (const Dbyte& a) const {
        return (int)(a.h<<4 + a.l);
    }
};

With my code i can do:

Dbyte db1, db2;
db1 = 20;
db2 = db1;

but i can't compile

int i = db1;

What i'm doing wrong?

2) Some of these Dbytes are bitfields (or the low nibble is a value and the high nibble is a bitfield). There's a handy way to access them as bit? I've just learned the existence of std::bitset but i still don't know how to use them, and in my dreams i would like to write something like

if (db1[6]==true) ...

or

if (db1.bit[6]==true) ...

There's a way to obtain something like this?

If this matters, i'm working with C++Builder 2006, but the project could be migrated in a QTQuick app, so i'd prefere a "stardard c++" solution.

Thanks

Was it helpful?

Solution

To convert your type to another, you need a conversion, not assignment, operator:

operator int() const {
    return (h<<4) + l;
}

For the opposite conversion, you would be better off with a converting constructor, rather than an assignment operator:

DByte(int i) : l(i & 0xf), h((i>>4) & 0xf) {}

This can be used for initialising a DByte as well as assigning to it:

DByte db = 42;  // not assignment - requires a constructor

Assignment still works with just this constructor, and no special assignment operator - an integer value can be converted using the constructor, then assigned with the implicit assignment operator.

Finally, there's no point writing your own copy constructor here. The implicit one does exactly the same thing.

OTHER TIPS

int operator = (const Dbyte& a) const tries to be a copy-assignment operator but can't be because it's const. What you wanted to write was: operator int() const

I think your overloaded = operator for int is out of scope because you placed it in the struct for DByte. For your Dbyte[i] == true concept, try overloading the [] operator to return a boolean.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top