Προς το περιεχόμενο

Προτεινόμενες αναρτήσεις

Δημοσ.

Παραθέτω κώδικα.

#include <climits> // CHAR_BIT
#include <cstdlib> // div, div_t
#include <iostream> // std::cout

class bitref;

class bitptr {
    friend class bitref;
public:
    bitptr(void *memory = nullptr, int offset = 0);
    bitptr& operator+=(int j);
    bitptr& operator-=(int j);
    bitptr& operator++();
    bitptr& operator--();
    bitptr operator++(int);
    bitptr operator--(int);
    bitptr operator+(int) const;
    bitptr operator-(int) const;
    bitref operator*() const;
    bitref operator[](int) const;
    bool operator==(const bitptr& rhs) const;
    bitptr& operator=(void *rhs);

private:
    unsigned char *p;
    int i;
};

class bitref {
public:
    bitref(const bitptr& p) : p(p.p), i(p.i) {};
    bitref& operator=(bool  {
        if (
            *p |= 1 << i;
        else
            *p &= ~(unsigned char)(1 << i);
        return *this;
    }
    bool operator==(bool  {
        return b == (*p & (1 << i));
    }
    explicit operator bool() const { return *p & (1 << i); }
private:
    unsigned char *p;
    int i;
};

bitptr::bitptr(void *memory, int offset) {
    div_t d;
    p = static_cast<unsigned char *>(memory);
    d = div(offset, CHAR_BIT);
    p += d.quot;
    i = d.rem;
}

bitptr& bitptr::operator+=(int j) {
    div_t d;
    d = div(j + i, CHAR_BIT);
    p += d.quot;
    i = d.rem;
    return *this;
}

bitptr& bitptr::operator-=(int j) {
    return *this += -j;
}

bitptr& bitptr::operator++() {
    if (++i == CHAR_BIT) ++p, i = 0;
    return *this;
}

bitptr& bitptr::operator--() {
    if (--i == -1) --p, i = CHAR_BIT - 1;
    return *this;
}

bitptr bitptr::operator++(int) {
    bitptr val{ *this };
    ++*this;
    return val;
}

bitptr bitptr::operator--(int) {
    bitptr val{ *this };
    --*this;
    return val;
}

bitptr bitptr::operator+(int j) const {
    bitptr val{ *this };
    val += j;
    return val;
}

bitptr bitptr::operator-(int j) const {
    bitptr val{ *this };
    val -= j;
    return val;
}

bitref bitptr::operator*() const {
    return bitref(*this);
}

bitref bitptr::operator[](int j) const {
    return *(*this + j);
};

bool bitptr::operator==(const bitptr& q) const {
    return p == q.p && i == q.i;
}

bitptr& bitptr::operator=(void *q) {
    p = static_cast<unsigned char *>(q);
    i = 0;
    return *this;
}

int main(void) {
    bitptr p;
    char c = 0;
    p = static_cast<void*>(&c);
    // 'A' = 01000001
    p[0] = 1;
    p[1] = 0;
    p[2] = 0;
    p[3] = 0;
    p[4] = 0;
    p[5] = 0;
    p[6] = 1;
    p[7] = 0;
    std::cout << c << std::endl; // Prints A
    return 0;
}

Δημιουργήστε ένα λογαριασμό ή συνδεθείτε για να σχολιάσετε

Πρέπει να είστε μέλος για να αφήσετε σχόλιο

Δημιουργία λογαριασμού

Εγγραφείτε με νέο λογαριασμό στην κοινότητα μας. Είναι πανεύκολο!

Δημιουργία νέου λογαριασμού

Σύνδεση

Έχετε ήδη λογαριασμό; Συνδεθείτε εδώ.

Συνδεθείτε τώρα
  • Δημιουργία νέου...