Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding 4 values in a 32-bit integer

Tags:

c++

c

I am trying to make a class that will encode 4 values in one 32-bit integer. So far, it saves and outputs all the values without losing anything, but for some reason, in the wrong order.

struct encoder {
    uint32_t val;

    encoder(uint32_t _val = 0) : val(_val) {}

    uint32_t first(uint32_t v = 0) {
        if (!v) return (val << (8*3)) >> (8*3);

        val |= v;
    }

    uint32_t second(uint32_t v = 0) {
        if (!v) return (val << (8*2)) >> (8*3);

        encoder _backupval(val);

        val = (val >> (8*1));
        val |= v;
        val = (val << (8*1));
        val |= _backupval.first();
    }

    uint32_t third(uint32_t v = 0) {
        if (!v) return (val << (8*1)) >> (8*3);

        encoder _backupval(val);

        val = (val >> (8*2));
        val |= v;
        //now restore
        val = val << 8;
        val |= _backupval.second();
        val = val << 8;
        val |= _backupval.first();
    }

    uint32_t fourth(uint32_t v = 0) {
        if (!v) return (val << (8*0)) >> (8*3);

        encoder _backupval(val);

        val = (val >> (8*3));
        val |= v;
        //now restore
        val = val << 8;
        val |= _backupval.second();
        val = val << 8;
        val |= _backupval.first();
        val = val << 8;
        val |= _backupval.third();
    }
};

int main() {
    encoder t;
    t.first(6);
    t.second(42);
    t.third(212);
    t.fourth(23);

    cout << "first number: " << t.first()
         << "\nsecond number: " << t.second()
         << "\nthird number: " << t.third()
         << "\nfourth number: " << t.fourth() << endl;

}

Note that I am doing this as an exercise, and this program is not going to be used in real programs. So do not suggest alternative ways to do it, and do not point out the flaws (like if the size of the number is more then 256, it will corrupt the other integer, etc.)

like image 710
user1507133 Avatar asked Mar 03 '26 11:03

user1507133


1 Answers

You mixed the order of functions in fourth:

uint32_t fourth(uint32_t v = 0) {
    if (!v) return (val << (8*0)) >> (8*3);

    encoder _backupval(val);

    val = (val >> (8*3));
    val |= v;
    //now restore
    val = val << 8;
    val |= _backupval.second();
    val = val << 8;
    val |= _backupval.first();
    val = val << 8;
    val |= _backupval.third();  // this should be called first!
}

This will result in the scrambled return values. Simply call third first and it will work:

uint32_t fourth(uint32_t v = 0) {
    if (!v) return (val << (8*0)) >> (8*3);

    encoder _backupval(val);

    val = (val >> (8*3));
    val |= v;
    //now restore
    val = val << 8;
    val |= _backupval.third();
    val = val << 8;
    val |= _backupval.second();
    val = val << 8;
    val |= _backupval.first();
}
like image 125
Zeta Avatar answered Mar 05 '26 02:03

Zeta