以32位整数编码4个值

时间:2012-08-03 13:25:59

标签: c++ c

我正在尝试创建一个将在一个32位整数中编码4个值的类。到目前为止,它保存并输出所有值而不会丢失任何内容,但出于某种原因,顺序错误。

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;

}

请注意,我这样做是为了练习,而且这个程序不会在真正的程序中使用。因此,不要建议其他方法,并且不要指出缺陷(如果数字的大小超过256,它将破坏其他整数等)。

1 个答案:

答案 0 :(得分:5)

您混合了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!
}

这将导致加扰返回值。只需先致电third,然后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();
}