我正在尝试创建一个将 4 个值编码为一个 32 位整数的类。到目前为止,它保存并输出了所有值而没有丢失任何东西,但是由于某种原因,顺序错误。
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,它会破坏另一个整数等)