merlin2011
merlin2011

Reputation: 75565

Is it possible to overload the indexing operator[] to return bits from an integer?

I am not sure whether this is possible because as far as I know, references cannot refer to individual bits in an integer, but I am curious to know whether there is a technique that will enable the following effect.

int z = 0x1234;
z[0] = 1; //set the most significant bit of z.
uint8_t bit = z[30] //get the index 30 bit of z, counting from the left.

If I cannot have z[0] = 1, I wonder if it is at least possible to be able to extract bits using the overloading operation.

Upvotes: 0

Views: 109

Answers (3)

Steve Jessop
Steve Jessop

Reputation: 279255

If you're going to wrap int, you could do it something like this:

class bitval {
    int &val;
    unsigned int mask;
  public:
    bitval(int &i, int idx) : val(i), mask(((unsigned int)(INT_MAX) + 1) >> idx) {}
    bitval &operator=(int i)  {
        if (i) {
            val |= mask;
        } else {
            val &= ~mask;
        }
        return *this;
    }
    operator bool() const {
        return val & mask;
    }
};

class bit {
    int &val;
  public:
    bit(int &i) : val(i) {}
    bitval operator[](int idx) { return bitval(val, idx); }
};

Then the syntax would be:

int z = 0x1234;
bit(z)[0] = 1;
uint8_t b = bit(z)[30];

Btw, C++ programmers usually refer to the least significant bit as bit 0, not the most significant bit, so mask(1 << idx) might make things less confusing for them.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

Not directly. You can either write a wrapper over int or use a std::bitset.

Upvotes: 5

Kerrek SB
Kerrek SB

Reputation: 477060

You cannot overload operators for built-in types. Overloaded operators must include at least one user-defined type (i.e. a class or union type).

Upvotes: 2

Related Questions